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
为什么?我怎样才能使它input()
正常工作?我试图编码/解码s1
,但它不起作用。
谢谢你。
如果您在 Windows 上,您会注意到input()
当您键入 's' 并 Enter 时的结果是"s\r"
. 从结果中删除所有尾随空格,你会没事的。
你没有说你使用的是哪个版本的 Python,所以我猜你使用的是在 Microsoft Windows 上运行的 Python 3.2。
这是一个已知的错误,请参阅http://bugs.python.org/issue11272 “input() 在 Windows 上有尾随回车”
解决方法包括使用不同版本的 Python,使用非 Windows 操作系统,或者从input()
. 您还应该知道迭代 stdin 有同样的问题。
首先,输入就像eval(raw_input())这意味着您传递给它的所有内容都将被评估为 python 表达式。我建议您改用 raw_input() 。
我测试了你的代码,它们对我来说是平等的:
import sys
s1 = input()
s2 = sys.stdin.read(1)
if s1==s2 and s1=="s":
print "They're both equal s"
这是输出:
flaper87@BigMac:/tmp$ python test.py
"s"
s
They're both equal s
使用 sys.stdin.read(1) 只会从标准输入读取 1 个字符,这意味着如果您传递“s”,则只会读取第一个“。有 sys.stdin.readline() 读取整行(包括最终\n)。