input() vs sys.stdin.read()

狂风中的少年 提交于 2021-02-07 13:44:00

问题


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/decode s1, but it doesn't work.

Thank you.


回答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.




回答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.




回答3:


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 sys
s1 = 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"
s
They'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).



来源:https://stackoverflow.com/questions/6055659/input-vs-sys-stdin-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!