[Tutor] Quick Question on String Compare

Danny Yoo dyoo at hashcollision.org
Sun Jun 2 07:53:31 CEST 2013


The standard sorting in Python depends on a comparison operator.  A
quick and easy comparison operator that Python uses for strings is
lexicographic ordering:

    http://en.wikipedia.org/wiki/Lexicographical_order

The quick and dirty rule is: dictionary order, with each character
consistently treated as a character.

As you note, this doesn't "look" right when we're comparing strings
with numbers.  That's a common problem.  Since it's not immediately
clear from the computer's point of view what to do here, Python has no
policy that favors humans.  To make comparison work the way you want
it to, you need to write it explicitly, as it does not come built-in.

See:

    http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

    http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort


More information about the Tutor mailing list