How to get user input for multiline lines in Pytho

2019-08-15 19:18发布

Total newb at this and tried to figure this out. I know that the regular input function can accept single lines, but as soon as you try to write a string paragraph and hit enter for the next line, it terminates. Is there a beginner friendly way to accept multiline user string inputs as variables? Thanks!

4条回答
女痞
2楼-- · 2019-08-15 19:28

A common way of doing this in programs is to have an "I'm done" string (e.g. a single period), and to keep reading in lines until the line read matches that string.

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)
查看更多
冷血范
3楼-- · 2019-08-15 19:31

You can do that using sys library

import sys
x = sys.stdin.read()
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-15 19:41
Line=""

while True:

    x=input()

    Line=Line+" "+x

    if "." in x:

        break

print(Line)
查看更多
该账号已被封号
5楼-- · 2019-08-15 19:52
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
查看更多
登录 后发表回答