HBR
HBR

Reputation: 13

Python ASCII values of a string

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

Upvotes: 1

Views: 6251

Answers (3)

Christian König
Christian König

Reputation: 3570

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.

Upvotes: 4

Mohanavel T
Mohanavel T

Reputation: 391

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.

Upvotes: 3

Kim
Kim

Reputation: 461

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].

Upvotes: 2

Related Questions