如何在Python中读取多行原始输入?

Ric*_*ckD 55 python user-input input

我想创建一个Python程序,它接受多行用户输入.例如:

This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
Run Code Online (Sandbox Code Playgroud)

如何接收多行原始输入?

jam*_*lak 79

sentinel = '' # ends when this string is seen
for line in iter(raw_input, sentinel):
    pass # do things here
Run Code Online (Sandbox Code Playgroud)

要将每一行作为字符串,您可以执行以下操作:

'\n'.join(iter(raw_input, sentinel))
Run Code Online (Sandbox Code Playgroud)

Python 3:

'\n'.join(iter(input, sentinel))
Run Code Online (Sandbox Code Playgroud)

  • 我已经做了大约6年的pythonista,我从来不知道`iter()`的另一种形式.你先生是天才! (8认同)
  • 如何将EOF设置为哨兵角色? (6认同)
  • @wecsam现在补充说,为所有蟒蛇做出答案 (3认同)
  • @Randy 你能不能看起来不那么漂亮`iter(lambda: raw_input('prompt'), sentinel)` (2认同)
  • 请注意,在Python 3中,`raw_input`现在是`input`. (2认同)

Jun*_*uxx 7

继续读取行,直到用户输入空行(或更改stopword为其他行)

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text
Run Code Online (Sandbox Code Playgroud)


小智 6

或者,您可以尝试 sys.stdin.read()

import sys
s = sys.stdin.read()
print(s)
Run Code Online (Sandbox Code Playgroud)

  • 如果您想要接收具有多个空行的文本或任何其他数据,那么此解决方案是完美的。当到达 EOF 时停止(Ctrl+D;Windows 上为 Ctrl+Z)。 (4认同)