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
54.5k13 gold badges84 silver badges120 bronze badges
asked Nov 4, 2017 at 0:58
1
  • 1
    Have a look at this 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. Commented Nov 4, 2017 at 1:06

3 Answers 3

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
answered Nov 4, 2017 at 1:11

Comments

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

answered Nov 4, 2017 at 1:11

Comments

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

answered Nov 4, 2017 at 1:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.