1
'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')?

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
JayHong
  • 49
  • 5
  • 1
    Have a look at [this](https://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python) post. Keep in mind that '2' is also a string and not a numerical value, more so its ASCII integer equivalent is smaller than `'a'` - which is true for all digits - and which is the reason why `'a'` than any digit. – atru Nov 04 '17 at 01:06

3 Answers3

1

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
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

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()).

Tiago1984
  • 61
  • 3
0

The comparison is by position, here is an example:

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

=> True

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

=> True

See docs here

developer_hatch
  • 15,898
  • 3
  • 42
  • 75