簡體   English   中英

如何在 Python 3 中獲取多行的用戶輸入?

[英]How to get user input for multiline lines in Python 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
import sys
s = sys.stdin.read()
# print(s) # It will print everything 
for line in s.splitlines(): # to read line by line
    print(line)
[input() for i in range(int(input()))]

對於 n 多行用戶輸入,列表中的每個索引都是用戶輸入的新行。

Line=""

while True:

    x=input()

    Line=Line+" "+x

    if "." in x:

        break

print(Line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM