I want to create a Python program which takes in multiple lines of user input. For example:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
How can I take in multiple lines of raw input?
I want to create a Python program which takes in multiple lines of user input. For example:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
How can I take in multiple lines of raw input?
sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here
要将每一行作为字符串,您可以执行以下操作:
'\n'.join(iter(input, sentinel))
蟒蛇2:
'\n'.join(iter(raw_input, sentinel))
或者,您可以尝试sys.stdin.read()
返回整个输入,直到EOF
:
import sys
s = sys.stdin.read()
print(s)
继续阅读行,直到用户输入一个空行(或更改stopword
为其他内容)
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
print text
只需扩展此答案https://stackoverflow.com/a/11664652/4476612 而不是任何停用词,您就可以检查是否有一行
content = []
while True:
line = raw_input()
if line:
content.append(line)
else:
break
您将获得列表中的行,然后加入 \n 以获得您的格式。
print '\n'.join(content)
*我自己在这个问题上苦苦挣扎了很长时间,因为我想找到一种方法来读取多行用户输入,而无需用户使用 Control D(或停用词)来终止它。最后,我在 Python3 中找到了一种方法,使用 pyperclip 模块(您必须使用 pip install 安装)以下是一个采用 IP 列表的示例 *
import pyperclip
lines = 0
while True:
lines = lines + 1 #counts iterations of the while loop.
text = pyperclip.paste()
linecount = text.count('\n')+1 #counts lines in clipboard content.
if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
ipaddress = input()
print(ipaddress)
else:
break
对我来说,这正是我想要的;接受多行输入,执行所需的操作(这里是简单的打印),然后在处理最后一行时中断循环。希望它对你也同样有帮助。
尝试这个
import sys
lines = sys.stdin.read().splitlines()
print(lines)
输入:
1
2
3
4
输出: ['1','2','3','4']
当您知道要让 python 读取的确切行数时,从提示/控制台读取多行的最简单方法是list comprehension。
lists = [ input() for i in range(2)]
上面的代码读取 2 行。并将输入保存在列表中。
Python Prompt Toolkit 实际上是一个很好的答案,但上面的示例并没有真正显示出来。一个更好的例子是示例目录中的get-multiline-input.py:
#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import HTML
def prompt_continuation(width, line_number, wrap_count):
"""
The continuation: display line numbers and '->' before soft wraps.
Notice that we can return any kind of formatted text from here.
The prompt continuation doesn't have to be the same width as the prompt
which is displayed before the first line, but in this example we choose to
align them. The `width` input that we receive here represents the width of
the prompt.
"""
if wrap_count > 0:
return " " * (width - 3) + "-> "
else:
text = ("- %i - " % (line_number + 1)).rjust(width)
return HTML("<strong>%s</strong>") % text
if __name__ == "__main__":
print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
answer = prompt(
"Multiline input: ", multiline=True, prompt_continuation=prompt_continuation
)
print("You said: %s" % answer)
使用此代码,您可以获得多行输入,即使在输入后续行之后,也可以在其中编辑每一行。还有一些不错的附加功能,例如行号。输入通过按退出键然后按回车键结束:
~/Desktop ❯ py prompt.py
按 [Meta+Enter] 或 [Esc] 然后按 [Enter] 接受输入。
多行输入:第一行文本,然后输入
- 2 - 第二行文本,然后输入
- 3 - 第三行文本,箭头键可以移动,输入
- 4 - 可以根据需要编辑行,直到您
- 5 - 按退出键,然后按回车键
你说:第一行文字,然后输入
第二行文字,然后输入
第三行文字,箭头键可以左右移动,输入
和行可以根据需要编辑,直到你
按退出键,然后按回车键
~/Desktop ❯</p>
你觉得这个怎么样?我模仿了telnet。该片段是高度不言自明的:)
#!/usr/bin/env python3
my_msg = input('Message? (End Message with <return>.<return>) \n>> ')
each_line = ''
while not each_line == '.':
each_line = input('>> ')
my_msg += f'\n{each_line}'
my_msg = my_msg[:-1] # Remove unwanted period.
print(f'Your Message:\n{my_msg}')
一种更简洁的方法(没有停用词 hack 或 CTRL+D)是使用Python Prompt Toolkit
然后我们可以这样做:
from prompt_toolkit import prompt
if __name__ == '__main__':
answer = prompt('Paste your huge long input: ')
print('You said: %s' % answer)
即使是长的多行输入,它的输入处理也非常有效。
它是在 python > 3.5 版本中编写代码的最佳方式
a= int(input())
if a:
list1.append(a)
else:
break
即使你想限制你可以去的值的数量
while s>0:
a= int(input())
if a:
list1.append(a)
else:
break
s=s-1
sys.stdin.read() 可用于从用户获取多行输入。例如
>>> import sys
>>> data = sys.stdin.read()
line one
line two
line three
<<Ctrl+d>>
>>> for line in data.split(sep='\n'):
print(line)
o/p:line one
line two
line three
使用 Python 3,您可以将每一行分配给data
:
while data := input():
print("line", data)
def sentence_maker(phrase):
return phrase
results = []
while True:
user_input = input("What's on your mind: ")
if user_input == '\end':
break
else:
results.append(sentence_maker(user_input))
print('\n'.join(map(str, results)))