如何从用户输入中读取直到在 Python 中找到换行符?

How to read from user input until newline is found in Python?

我想从用户那里获取未知数量的正整数和负整数。当用户按下回车键时,输入将停止。

例如- 如果用户输入 1 2 3 4 5 -9 -10 1000 -Enter Key-
那么它将存储 "1 2 3 4 5 -9 -10 1000"

这是我试过的代码 -

a = []
inp = input()

while inp != "\n":
    a.append(inp)
    inp = input()

print(a)

但这并不是在按下回车键后停止输入。

编辑 - This 问题要求输入直到空输入,但我的问题是在一行中输入直到用户按下 Enter 按钮。

改成

while inp:
    a.append(inp)
    inp = input()

输入换行时,inp为空串,即,从而打破循环。

如果您使用的是 Python 3.8,您可以在此处使用 walrus 运算符

ls = []

while (inp := input("> ")):
    ls.append(inp)

print(ls)