raw_input 如何处理 ENTER 或 \n

How does raw_input treat ENTER or \n

我有一长串数字,我想通过 raw_input 输入到我的代码中。它包括通过 SPACESENTER/RETURN 隔开的数字。该列表看起来像 this 。当我尝试使用函数 raw_input 并复制粘贴一长串数字时,我的变量只保留第一行数字。到目前为止,这是我的代码:

def main(*arg):
    for i in arg:
        print arg

if __name__ == "__main__": main(raw_input("The large array of numbers"))

如何让我的代码继续读取剩余的数字? 或者,如果那不可能,我可以让我的代码以任何方式确认 ENTER 吗?

P.s。虽然这是一个项目欧拉问题,但我不想要回答项目欧拉问题的代码,或者对数字进行硬编码的建议。只是将数字输入我的代码的建议。

我认为您真正想要的是通过 sys.stdin 直接从 stdin 读取。但是你需要接受这样一个事实,即应该有一种机制来停止接受来自 stdin 的任何数据,在这种情况下,通过传递一个 EOF 字符是可行的。 EOF 字符通过组合键 [CNTRL]+d

传递
>>> data=''.join(sys.stdin)
Hello
World
as
a
single stream
>>> print data
Hello
World
as
a
single stream

如果我没有正确理解你的问题,我认为这段代码应该可以工作(假设它在 python 2.7 中):

sentinel = '' # ends when this string is seen
rawinputtext = ''
for line in iter(raw_input, sentinel):
    rawinputtext += line + '\n' #or delete \n if you want it all in a single line
print rawinputtext

(代码取自:Raw input across multiple lines in Python

PS:或者更好的是,您可以在一行中完成同样的操作!

rawinputtext = '\n'.join(iter(raw_input, '') #replace '\n' for '' if you want the input in one single line

(代码取自: