我想创建一个需要多行用户输入的Python程序。例如:如何读取Python中的多行原始输入?
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
如何接受多行原始输入?
我想创建一个需要多行用户输入的Python程序。例如:如何读取Python中的多行原始输入?
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
如何接受多行原始输入?
sentinel = '' # ends when this string is seen
for line in iter(raw_input, sentinel):
pass # do things here
要得到每行作为一个字符串,你可以这样做:
'\n'.join(iter(raw_input, sentinel))
的Python 3:
'\n'.join(iter(input, sentinel))
我已经约6年pythonista,我从来不知道的这个'iter()'的另一种形式。你的先生是一个bl dy天才! – inspectorG4dget 2013-10-12 07:40:19
如何将EOF设置为标记字符? – MadTux 2014-01-16 15:42:52
@jamylak - 这是否允许在'raw_input'中提示?好像你不能在第一个参数'iter'中传递参数给函数。 – Randy 2014-06-03 20:34:21
继续读线,直到用户输入一个空行(或更改stopword
到别的)
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
print text
或者,你可以尝试sys.stdin.read()
import sys
s=sys.stdin.read()
print s
请提供更详细地,如示出了如何使用此功能的示例代码。 – 2017-11-02 15:35:06
只是扩展这个答案https://stackoverflow.com/a/11664652/4476612 而不是任何停止词你可以检查线路是否存在与否
content = []
while True:
line = raw_input()
if line:
content.append(line)
else:
break
你会得到列表中的行,然后加入\ n以获得您的格式。
print '\n'.join(content)
如果您正在进行多行输入,您如何知道输入何时结束? – Blckknght 2012-07-26 07:31:35
有一个循环需要raw_input,直到用户输入'done'或其他东西。 – Pramod 2012-07-26 07:41:58
我想你的目标用户输入,但您可以添加换行符\ n的提示,如:的raw_input(“富\ NBAR:”) – 2012-07-26 07:47:00