input() 与 sys.stdin.read()
import sys
s1 = input()
s2 = sys.stdin.read(1)
#type "s" for example
s1 == "s" #False
s2 == "s" #True
为什么?如何使input()
正常工作? 我尝试对 s1
进行编码/解码,但不起作用。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是 Windows,您会注意到,当您键入 's' 并按 Enter 时,
input()
的结果是"s\r"
。从结果中去除所有尾随空格,就可以了。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.您没有说明您使用的是哪个版本的 Python,因此我猜测您使用的是在 Microsoft Windows 上运行的 Python 3.2。
这是一个已知错误,请参阅 http://bugs.python.org/issue11272 “input() 具有尾随Windows 上的回车符”
解决方法包括使用不同版本的 Python、使用非 Windows 操作系统,或者从
input()
返回的任何 string() 中删除尾随回车符。您还应该意识到迭代 stdin 也有同样的问题。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.首先,输入类似于 eval(raw_input()) 这意味着您传递的所有内容它将被评估为 python 表达式。我建议您改用 raw_input() 。
我测试了你的代码,它们对我来说是相等的:
这是输出:
使用 sys.stdin.read(1) 只会从标准输入中读取 1 个字符,这意味着如果你传递“s”,则只会读取第一个“ sys.stdin.readline() 读取整行(包括最后的 \n)。
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:
This is the output:
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).