当我尝试从标准输入读取多个中间有空格的字符串时,为什么会在 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使用的是Python2.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']
您可以详细了解 input
和 raw_input
here 之间的区别。
我不知道为什么我的在线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使用的是Python2.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']
您可以详细了解 input
和 raw_input
here 之间的区别。