JayHong
JayHong

Reputation: 49

Comparing string numerical values in python

'a' > str('2')         # True
'a' > str('34363454')  # True
'a' > 'b'              # False
'a' < 'b'              # True

I thought the value of string a is the same as ord('a'), which is 97.

I would like to know how to compare different strings with the Boolean expressions.

Why is b greater than a? Why is a greater than str('2')?

Upvotes: 1

Views: 189

Answers (3)

developer_hatch
developer_hatch

Reputation: 16224

The comparison is by position, here is an example:

print("b">"a1234a"); # b > a

=> True

print("a">"1234a"); # a > 1

=> True

See docs here

Upvotes: 0

Tiago1984
Tiago1984

Reputation: 61

In Python, all variables are, implemented as pointers to memory regions that store their actual data. Their behavior is defined according to arbitrary rules. Comparing strings, for example, is defined as comparing them alphabetically (a>b is true if a comes later in the dictionary), so you have:

>>> "stack" > "overflow"
True

'a' == 97 is something found when a char type (not a string 'a') is represented as a number indicating a position in the ASCII table (which is the case, for example, of C, or, in Python, something that can be found using ord()).

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54243

As you said, string comparisons can be thought of as mapping ord over the results and comparing the resulting lists.

'23' > '33' = map(ord, '23') > map(ord, '33')
            = (50, 51) > (51, 51)
            = False

Similarly

ord('a') = 97
ord('b') = 98
# and so...
'a' < 'b'        # True

Note that capitals throw a monkey wrench in things

'Z' < 'a'  # True
'a' < 'z'  # also True

Upvotes: 1

Related Questions