0

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...
Hashshashin
  • 27
  • 1
  • 7
clink
  • 213
  • 3
  • 11
  • 3
    Python string support comparaison: `'a' < 'b'` equals `True`. – TwistedSim May 04 '18 at 15:16
  • Possible duplicate of [String comparison technique used by Python](https://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python) – William Perron May 04 '18 at 15:17
  • 1
    Is there some difference between "alphabetically smaller" and "lexicographically smaller"? Python does the latter automatically. Are you worried about capitalization or accents or something similar? Are you using a collating sequence other than Unicode? – Rory Daulton May 04 '18 at 15:17
  • you can compare the .lower() versions if you are worried about caps – Grady Player May 04 '18 at 15:21
  • Unless you mean lexicographically, you need to know a few things to start: character encoding, language/culture/locale, and desired case sensitivity; Fixed ones or user's settings or choice? – Tom Blodget May 05 '18 at 18:45

1 Answers1

3

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']
TwistedSim
  • 1,960
  • 9
  • 23