"3" < "4" evaluates True but "3" < "10" evaluates False. why?

print("3" < "10") #This prints False
print("3" < "4") #This prints True

How is it possible to compare numbers inside of a string, and why one is True and the other False when in the case of being poissible to compare numbers inside a string both should be True?

I came across this while doing an exercise of progamarcadegames.com and I'm using python 3.3.3 shell

Upvotes: 2

Views: 182

Answers (4)

sameh.q
sameh.q

Reputation: 1709

In strings, comparison works from left to right, a character by character, if the characters that are being compared are the same, the next one will be compared

Ex:

"1" will be evaluated less than "3"

Also, "01000" will be less than "1" for the same reason

To compare them as numbers, they must be converted to numbers

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121416

You are comparing strings; these are sorted lexicographically.

Since '1' comes earlier in the ASCII standard than '3', the string '10' is sorted before '3' and considered lower, just like 'Martijn' would be sorted before 'Rodrigo' based on the letter 'M' coming before the letter 'R', but 'jco' would be sorted after 'Martijn' since lowercase characters are listed after uppercase letters in the ASCII standard.

Convert your values to integers if you want to compare them numerically instead.

Upvotes: 10

Qiau
Qiau

Reputation: 6175

In the question you are comparing two strings as you said yourself. Each string will be compared by ASCII value for each char where 1 in 10 is less than 3.

>>> ord('1')
49
>>> ord('3')
51
>>> ord('4')
52

If you need to convert a string to the number you can use int(str):

>>> print(int("3") < int("10"))
True
>>> print(int("3") < int("4"))
True
>>> 

Otherwise you are comparing the string values.

Upvotes: 2

Romo Daneghyan
Romo Daneghyan

Reputation: 2169

If you want to compare numbers inside strings, you have to convert them into numbers like this int("3") for example, and then compare their numeric values.

Upvotes: 0

Related Questions