1

我知道常规输入函数可以接受单行,但是一旦您尝试编写字符串段落并按 Enter 键输入下一行,它就会终止。是否有一种适合初学者的方式来接受多行用户字符串输入作为变量?

4

6 回答 6

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)
于 2012-10-29T20:18:17.670 回答
1

您可以使用 sys 库来做到这一点

import sys
x = sys.stdin.read()
于 2017-02-12T22:13:15.227 回答
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)
于 2020-08-25T03:18:28.277 回答
0
[input() for i in range(int(input()))]

对于 n 个多行用户输入,列表中的每个索引都是来自用户的新行输入。

于 2021-12-14T06:13:41.480 回答
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
于 2017-10-19T17:47:06.110 回答
-2
Line=""

while True:

    x=input()

    Line=Line+" "+x

    if "." in x:

        break

print(Line)
于 2017-06-20T10:40:05.970 回答