-1

So, I have been working in some problems that require that the code organize a string in alphabetical order, so my first thoughts were to try using char comparisons. If charA < charB and all that, but couldn't make it. But I guess I don't really know how the char comparison Works.

Need a simple explanation on how they work. Thank you!

Santiago Isaza
  • 3
  • 1
  • 1
  • 6
  • try out `ord()` and `chr()` – JacobIRR Jun 18 '18 at 23:15
  • If `charA` and `charB` are actually characters (that is, length-1 strings), then `charA < charB` iff `ord(charA) < ord(charB)`. That is, if the Unicode code point of charA is a smaller number than the Unicode code point of charB, it's a smaller character. – abarnert Jun 18 '18 at 23:16
  • In short: each character has an ASCII value. The ASCII values of the characters are compared. – The Niv Jun 20 '20 at 06:31

2 Answers2

1

When you compare chars, their ordinal values are compared

So 'a' < 'b' just means ord('a') < ord('b')

Sunitha
  • 11,777
  • 2
  • 20
  • 23
1

If charA and charB are actually characters (that is, length-1 strings), then charA < charB iff ord(charA) < ord(charB).

That is, if the Unicode code point of charA is a smaller number than the Unicode code point of charB, it's a smaller character.

Notice that this means that 'Z' < 'a', because in Unicode, all of the capital letters A-Z come before the lowercase letters a-z:

>>> ord('A')
65
>>> ord('Z')
90
>>> ord('a')
97
>>> 90 < 97 # of course
True
>>> 'Z' < 'a' # possibly surprising
True

If you want some kind of "friendly" comparison, you have to ask for it explicitly.

Often, you just want casefold, which aggressively gets rid of case information, so that, e.g., A and a can be treated the same:

>>> 'A'.casefold()
'a'
>>> 'Z'.casefold() < 'a'.casefold()
False

For full generality, you probably want something like the Unicode Collation Algorithm. But Python doesn't come with that built in, so you'd need a third-party library like pyuca.

abarnert
  • 354,177
  • 51
  • 601
  • 671