Reputation: 213
How do I perform the comparison between two strings to determine which is alphabetically smaller?
Example, if I have strings 'aberr'
and 'aftward'
how do I determine which is alphabetically smaller? Another example would be 'beast'
and 'best'
.
Do I have to make the strings into it's ascii representation such as:
ascii a + ascii b + ascii e...
Upvotes: 0
Views: 7697
Reputation: 2030
You can do string comparison in Python:
>>> min('aberr', 'aftward')
'aberr'
and
>>> min('beast', 'best')
'beast'
EDIT
As Grady Player points out, A
come after z
. You'll need to lower the string like this:
>>> min('aaaa', 'Bbbb')
'Bbbb'
>>> min('aaaa'.lower(), 'Bbbb'.lower())
'aaaa'
If you want to keep the string like it was, you'll need to use the key
attribute of min
:
>>> min('Aaaa', 'bbbb', key=lambda s: s.lower())
'Aaaa'
You can also sort them:
>>> sorted(['Aaaa', 'bbbb', 'cbaaa', 'bcaaa'], key=lambda s: s.lower())
['Aaaa', 'bbbb', 'bcaaa', 'cbaaa']
Upvotes: 3