input() 与 sys.stdin.read()

发布于 2024-11-08 05:47:43 字数 217 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无悔心 2024-11-15 05:47:43

如果您使用的是 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.

罪#恶を代价 2024-11-15 05:47:43

您没有说明您使用的是哪个版本的 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.

幸福还没到 2024-11-15 05:47:43

首先,输入类似于 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)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文