LuTengteng LuTengteng - 4 months ago 15
Python Question

Where's the difference of those two same 'str'

Here is a little piece of code:

from random import randint
code = "%d%d%d " % (randint(1, 9), randint(1, 9), randint(1, 9))
print(code)
guess = input("[keypad]> ")
print(guess == code)


I'll input the same number as the code printed, but why the last line code print False!

Doesn't the code and guess are the same str data?

Answer

You put a space at the end of your random-generated code value:

code = "%d%d%d " % (randint(1, 9), randint(1, 9), randint(1, 9))
#             ^

That space is significant; most people won't see the space and not enter it at the prompt:

>>> from random import randint
>>> code = "%d%d%d " % (randint(1, 9), randint(1, 9), randint(1, 9))
>>> code
'634 '
>>> '634' == code
False
>>> '634 ' == code
True

Either remove that extra space, or make sure you enter the space at the prompt:

>>> guess = input("[keypad]> ")
[keypad]> 634
>>> guess  # note the extra space I entered!
'634 '
>>> guess == code
True