如何在Python 3中获取多行行的用户输入?

时间:2012-10-29 20:13:58

标签: python string function input multiline

总计新闻并尝试解决这个问题。我知道常规输入功能可以接受 单行,但是一旦你尝试写一个字符串段落并按下Enter键进入下一行,它就会终止。是否有一种初学者友好的方式来接受多行用户字符串输入作为变量?谢谢!

5 个答案:

答案 0 :(得分:2)

在程序中执行此操作的常用方法是使用“我已完成”字符串(例如,单个句点),并继续读取行,直到读取的行与该字符串匹配为止。

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)

答案 1 :(得分:0)

您可以使用sys库

来实现
import sys
x = sys.stdin.read()

答案 2 :(得分:0)

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

答案 3 :(得分:0)

import sys
s = sys.stdin.read()
# print(s) # It will print everything 
for line in s.splitlines(): # to read line by line
    print(line)

答案 4 :(得分:-2)

Line=""

while True:

    x=input()

    Line=Line+" "+x

    if "." in x:

        break

print(Line)