When I was studying for the Python engineer certification exam, I understood what I could not understand by comparing character strings by comparison operation, so I will summarize it.
>>> 'ABC'<'C'<'Pascal'<'Python'
True
Why is the above comparison True
?
→ Because the character code
is compared
In the first place, the character code point is preset by python. You can easily check it with ʻord (string) . For example, ʻord ('a')
is 97, ʻord ('A') is 65, and so on. The above string comparison compares these numbers. However, even when comparing the code points of strings, ʻord ('ABC')
returns a type error.
>>> 'ABC'<'C'<'Pascal'<'Python'
True
Note that the string comparison compares the points of the first character code.
ʻOrd ('A') = 65 <ʻord ('C') = 67
.
Since'Pascal'and'Python' start with'P', we will continue to compare the letters'a'and'y'.
Since ʻord ('a') = 97 <ʻord ('y') = 121
,'Pascal'<'Python'is correct.
Recommended Posts