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

2024-05-15 03:45:36 发布

您现在位置:Python中文网/ 问答频道 /正文

完全是新手,想弄清楚这一点。我知道常规输入函数可以接受 单行,但只要您尝试编写一个字符串段落并按回车键进入下一行,它就会终止。有没有一种初学者友好的方法来接受多行用户字符串输入作为变量?谢谢!


Tags: 方法函数字符串用户常规段落单行初学者
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

相关问题 更多 >

    热门问题