繁体   English   中英

当我尝试从标准输入读取多个中间有空格的字符串时,为什么在 Python 中出现错误?

[英]Why do I get an error in Python when I try to read several strings with spaces in between from stdin?

不知道为什么我的网上ide在执行这段代码的时候会报错:

n = int(input())

lst = []

for i in range(n):
    lst.append(input())

print(lst)

当我将这些作为输入时:

5
first string
second string
third string
almost done
done now

我收到此错误:

$python main.py
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    lst.append(input())
  File "<string>", line 1
    first string
               ^
SyntaxError: invalid syntax

有趣的是,我在 VS Code 上使用相同的输入运行相同的代码并且没有遇到任何错误,甚至得到了结果:

['first string', 'second string', 'third string', 'almost done', 'done now']

发生了什么? 我很困惑...

问题是在线IDE使用Python 2.7,您需要使用raw_input()来正确处理输入。 你需要这样的东西:

n = int(input())

lst = []

for i in range(n):
    lst.append(raw_input().strip())

print(lst)
# prints ['first string', 'second string', 'third string', 'almost done', 'done now']

您可以在此处阅读有关inputraw_input之间区别的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM