x74x61
x74x61

Reputation: 433

Comparing strings in Python 3.2 difficulties

I have the following

if('y' == input("Enter y to continue")):
    # do something

But it doesn't work, no matter what I type?

Upvotes: 1

Views: 550

Answers (5)

Max Edgson
Max Edgson

Reputation: 11

I've just come across this issue, this is how I solved it (Python 3.4.1):

i = input ('Enter y to continue: ')
validity = i == 'y'

if validity == True:
    #do something

By using the Boolean type to identify whether the input was equal to y you are avoiding the bug, it's extremely simple too.

Upvotes: 1

Dan D.
Dan D.

Reputation: 74645

use if input("Enter y to continue").lower().startswith('y'):.

Upvotes: 0

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

This is a known bug on windows, you can identify it by doing print(repr(input("put y: "))

Try this

input("put y:").strip().lower() == "y"

Upvotes: 3

Giacomo Lacava
Giacomo Lacava

Reputation: 1823

Works fine for me on 3.2.1 on Windows 7 x64:

>>> if input("Enter y to continue") == 'y': print("ok")
Enter y to continuey
ok

("continuey" is correct, it's just "continue" + my "y" input.)

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

I can't reproduce this here:

>>> if('y' == input("Enter y to continue: ")):
...    print("Yeah!")
...
Enter y to continue: y
Yeah!
>>>

But I would do it differently anyway:

answer = input("Enter y to continue: ")
if answer.lower().startswith("y"):
   print("Yeah!")

also handles Y, Yes!, yes, please... etc. correctly.

Upvotes: 3

Related Questions