[英]How to get user input for multiline lines in Python 3?
我知道常规输入函数可以接受单行,但是一旦您尝试编写一个字符串段落并按下回车键进入下一行,它就会终止。 是否有一种初学者友好的方式来接受多行用户字符串输入作为变量?
在程序中执行此操作的一种常见方法是使用“I'm done”字符串(例如单个句点),并继续逐行读取,直到读取的行与该字符串匹配。
print("Enter as many lines of text as you want.")
print("When you're done, enter a single period on a line by itself.")
buffer = []
while True:
print("> ", end="")
line = input()
if line == ".":
break
buffer.append(line)
multiline_string = "\n".join(buffer)
print("You entered...")
print()
print(multiline_string)
你可以使用 sys 库来做到这一点
import sys
x = sys.stdin.read()
def processString(x):
print(x.replace('process','whatever'))
lines = ""
while True:
if lines == "":
lines = ""
print("Enter string:")
x = input()
if x == "" and lines != "":
processString(lines)
break
else:
lines += x
# then hit enter once after multi-line string to process it
import sys
s = sys.stdin.read()
# print(s) # It will print everything
for line in s.splitlines(): # to read line by line
print(line)
[input() for i in range(int(input()))]
对于 n 多行用户输入,列表中的每个索引都是用户输入的新行。
Line=""
while True:
x=input()
Line=Line+" "+x
if "." in x:
break
print(Line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.