Why doesn't the result from sys.stdin.readline() compare equal when I expect it to?
Question:
I m trying to compare keyboard input to a string:
import sys
# read from keyboard
line = sys.stdin.readline()
if line == "stop":
print 'stop detected'
else:
print 'no stop detected'
When I type ‘stop’ at the keyboard and enter, I want the program to print ‘stop detected’ but it always prints ‘no stop detected’. How can I fix this?
Answers:
sys.stdin.readline()
includes the trailing newline character. Either use raw_input()
, or compare line.rstrip("n")
to the string you are looking for (or even line.strip().lower()
).
I m trying to compare keyboard input to a string:
import sys
# read from keyboard
line = sys.stdin.readline()
if line == "stop":
print 'stop detected'
else:
print 'no stop detected'
When I type ‘stop’ at the keyboard and enter, I want the program to print ‘stop detected’ but it always prints ‘no stop detected’. How can I fix this?
sys.stdin.readline()
includes the trailing newline character. Either use raw_input()
, or compare line.rstrip("n")
to the string you are looking for (or even line.strip().lower()
).