"raw_input如何处理ENTER或\n"

2024-05-06 16:59:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的数字列表,我想通过一个原始的输入输入输入到我的代码中。它包括通过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"))

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

注:虽然这是一个ProjectEuler问题,但我不希望代码能回答ProjectEuler问题,也不希望有人建议对数字进行硬编码。只是建议把数字输入我的代码。在


Tags: 函数代码列表inputrawreturnmainarg
2条回答

我想你真正想要的是通过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

如果我正确地理解了您的问题,我认为这段代码应该可以工作(假设它是在Python2.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:或者更好,你可以在一行里做同样的事情!在

^{pr2}$

(代码取自:Input a multiline string in python

相关问题 更多 >