且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-23 13:18:50

在程序中执行此操作的常用方法是使用我完成字符串期间),并继续阅读,直到读取的行匹配该字符串。

  print(输入尽可能多的文本行)
print(完成后,单独输入一个单独的句点。)

buffer = []
True:
print(>,end =)
line = input()
if line ==。:
break
buffer.append( )
print()
print(multiline_string)
multiline_string =\\\
.join(buffer)

print(You entered ... )


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!

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)