簡體   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