1

Beginner's question - I know that '10' > '8' is False, and I know that the ASCII value of '8' is 56, but what is the value of '10'?

2
  • asciitable.com Commented Jan 23, 2019 at 7:07
  • According to table it is 49 48? Commented Jan 23, 2019 at 7:09

3 Answers 3

4

Sorting strings is done lexicographically, which means you compare character-wise from the beginning. The reason why '10' > '8' yields False is based on the per-character comparison: 1 has a smaller ASCII value than 8, so the following characters are ignored. If these characters happen to be equal, the next characters are compared, until a difference is found or you reach the end of one string. In this special case, where one is the beginning (prefix) of the other, the shorter one is considered "smaller". ('foot' < 'football').

'10' has no single ASCII value, since it is composed of two characters: '1' (ASCII value 49) and '0' (ASCII value 48).

Maybe have a look at the ord() and chr() functions.

Sign up to request clarification or add additional context in comments.

6 Comments

@Amadan, I have corrected my answer. Thanks for pointing out the mistake!
Thanks for the quick answer. But, then why is '010'<'10' True?
because '0'<'1'.
Same reason: character-wise comparison. You compare '0' to '1', which is smaller.
You compare character-wise from the beginning. If the characters are not equal, you have your answer. If they are equal, you look at the next characters. Added it to the answer.
|
3

Python compares string lexicographically i.e using ASCII value of the characters.

Here you are not comparing the numbers 10 and 8. You're comparing the string '10' with '8'.

It is string comparison/ordering (i.e) you only order(alphabetical) the strings with the first character right?

That's what is done here. Here it compares the 8 and 1 rather than 10. 1 happens before 8 in the ascii table. 1 is obviously not greater than 8. That's why you get False.

Use int('10') if your intention is to do numerical comparison.

Comments

2

Each character has its own ASCII value. The ASCII value of '1' is 49 and the ASCII value of '0' is 48. The ASCII values for '10' could be represented as [49, 48].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.