Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python input()与sys.stdin.read()的比较_Python_Python 3.x_Input_Python 3.2 - Fatal编程技术网

Python input()与sys.stdin.read()的比较

Python input()与sys.stdin.read()的比较,python,python-3.x,input,python-3.2,Python,Python 3.x,Input,Python 3.2,为什么??如何使input()正常工作? 我试图编码/解码s1,但不起作用 谢谢。您没有说您使用的是哪个版本的Python,所以我猜您使用的是运行在Microsoft Windows上的Python 3.2 这是一个已知的错误,请参见“input()在windows上有尾随回车” 解决方法包括使用不同版本的Python,使用非windows的操作系统,或者从input()返回的任何字符串()中剥离尾随回车符。您还应该知道,在stdin上迭代也有同样的问题。如果您在Windows上,您会注意到当您

为什么??如何使
input()
正常工作? 我试图编码/解码
s1
,但不起作用


谢谢。

您没有说您使用的是哪个版本的Python,所以我猜您使用的是运行在Microsoft Windows上的Python 3.2

这是一个已知的错误,请参见“input()在windows上有尾随回车”


解决方法包括使用不同版本的Python,使用非windows的操作系统,或者从
input()
返回的任何字符串()中剥离尾随回车符。您还应该知道,在stdin上迭代也有同样的问题。

如果您在Windows上,您会注意到当您键入“s”并输入时,
input()
的结果是
“s\r”
。从结果中去掉所有尾随的空格,您就可以了。

首先,输入是这样的,这意味着您传递给它的所有内容都将作为python表达式进行计算。我建议您改用raw_input()

我测试了你的代码,它们对我来说是平等的:

import sys
s1 = input()
s2 = sys.stdin.read(1)

#type "s" for example

s1 == "s" #False
s2 == "s" #True
这是输出:

import sys
s1 = input()
s2 = sys.stdin.read(1)

if s1==s2 and s1=="s":
    print "They're both equal s"

使用sys.stdin.read(1)将只从stdin中读取1个字符,这意味着如果您通过“s”,将只读取第一个字符。sys.stdin.readline()将读取整行(包括最后一行\n).

我猜你在最后两行中把s1和s2混在一起了?试着执行代码。对我来说很好。你真的在s周围加了引号吗?你使用的是什么操作系统/版本的python?是的,在windows上是3.2版。谢谢你的解释。问题解决了。关于“使用不同版本的python”的建议,我看到了Python 3.2.1rc1已经发布,因此如果您不介意使用一个发行候选版本进行次要的点修复,您可以升级到该版本,问题就解决了。请注意,在评论我的答案@fogbit确认他们使用的是Python 3.2 where
input()
是正确的用法。您的建议只适用于早期版本的Python。您是对的。当我发布答案时,我不知道Python版本。我应该问一下。谢谢^^
flaper87@BigMac:/tmp$ python test.py 
"s"
s
They're both equal s