[Tutor] Quick Question on String Compare
Peter Otten
__peter__ at web.de
Sat Jun 1 09:43:17 CEST 2013
Sarma Tangirala wrote:
> I had a quick question on how string compare works. If did '1001' <= '999'
> I get true. I know how the string compare works but I was wondering why it
> were so. Why doesn't the string length factor into the comparison? For
> example, If I compared character-by-character but also found how different
> the lengths are, I could avoid a wrong logical answer as in the example
> above. Any thoughts?
If you took the string length into acount you would get the "wrong logical
answer" for strings that don't look like numbers:
>>> number_strings = ["2", "20", "100", "1"]
>>> sorted(number_strings, key=lambda x: (len(x), x))
['1', '2', '20', '100']
>>> names = ["Abe", "Peter", "Pete", "Jim", "Jack"]
>>> sorted(names, key=lambda x: (len(x), x))
['Abe', 'Jim', 'Zoe', 'Jack', 'Pete', 'Peter']
There is no one sort order that fits all use cases, but Python makes it easy
to supply a custom key function that fits your needs.
More information about the Tutor
mailing list