input() vs sys.stdin.read()
Solution 1
If you're on Windows, you'll notice that the result of input()
when you type an 's' and Enter is "s\r"
. Strip all trailing whitespace from the result and you'll be fine.
Solution 2
You didn't say which version of Python you are using, so I'm going to guess you were using Python 3.2 running on Microsoft Windows.
This is a known bug see http://bugs.python.org/issue11272 "input() has trailing carriage return on windows"
Workarounds would include using a different version of Python, using an operating system that isn't windows, or stripping trailing carriage returns off any string() returned from input()
. You should also be aware that iterating over stdin has the same problem.
fogbit
Updated on July 31, 2020Comments
-
fogbit almost 4 years
import sys s1 = input() s2 = sys.stdin.read(1) #type "s" for example s1 == "s" #False s2 == "s" #True
Why? How can I make
input()
to work properly? I tried to encode/decodes1
, but it doesn't work.Thank you.
-
fogbit almost 13 yearsYes, it's version 3.2 on windows. Thank you for explanation. Problem solved.
-
Duncan almost 13 yearsOn the 'use a different version of Python' suggestion, I see that Python 3.2.1rc1 has been released, so if you don't mind using a release candidate for a minor point fix you can just upgrade to that version and the issue is fixed. See python.org/download/releases/3.2.1
-
Duncan almost 13 yearsNote that when commenting on my answer @fogbit confirmed they are using Python 3.2 where
input()
is the correct thing to use. Your advice would only apply for earlier versions of Python. -
FlaPer87 almost 13 yearsYou're right. When I posted my answer I didn't know the python version. I should've asked. Thanks ^^