input() vs sys.stdin.read() input() vs sys.stdin.read() python-3.x python-3.x

input() vs sys.stdin.read()


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.


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.


First, input is like eval(raw_input()) which means that everything you pass to it will be evalualted as a python expresion. I suggest you to use raw_input() instead.

I tested your code and they're equal for me:

import syss1 = input()s2 = sys.stdin.read(1)if s1==s2 and s1=="s":    print "They're both equal s"

This is the output:

flaper87@BigMac:/tmp$ python test.py "s"sThey're both equal s

Using sys.stdin.read(1) will read just 1 character from the stdin which means that if you pass "s" just the first " will be read. There's sys.stdin.readline() which reads the whole line (including the final \n).