I'm wondering how Python does string comparison, more specifically how it determines the outcome when a less than <
or greater than >
operator is used.
For instance if I put print('abc' < 'bac')
I get True
. I understand that it compares corresponding characters in the string, however its unclear as to why there is more, for lack of a better term, "weight" placed on the fact that a
is less thanb
(first position) in first string rather than the fact that a
is less than b
in the second string (second position).
Many people ask this question when the strings contain representations of numbers, and want to compare the numbers by numeric value. The straightforward solution is to convert the values first. See How do I parse a string to a float or int? . If there are multiple numbers in a list or other collection, see How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)? for batch conversion.
If you are trying to compare strings that contain digit sequences, treating the digits as if they were numeric (sometimes called "natural sort"), see Is there a built in function for string natural sort? .