【问题标题】:how can i do multiple lines of an input field? PYTHON [duplicate]我怎样才能做多行输入字段?蟒蛇[重复]
【发布时间】:2021-05-11 04:00:45
【问题描述】:

蟒蛇

input(write some text: )

我希望它输出的是:

write some text: it was a good day
today as i went to a park

然后按两次回车键继续执行其他代码行

【问题讨论】:

标签: python user-input


【解决方案1】:
print("enter 'quit' at end of your text")
print("type your text here")
# declare variable to strore string
text = ""
stop_word = "quit"
while True:
    line = input()
    if line.strip() == stop_word:
        break
    # \n is new line, %s is string formatting
    # str.strip() will remove any whitespace that is at start or end
    text += "%s\n" % line.strip()
print(text)

如果你想使用 3 个空行 作为停用词:

print("Please enter 3 blank lines to terminate")
print("type your text here")
# declare variable to strore string
text = ""
stop_word = "quit"
counter = 0
while True:
    line = input()
    if line.strip() == '':
        counter += 1
        if counter == 3:
            break
    # \n is new line, %s is string formatting
    # str.strip() will remove any whitespace that is at start or end
    text += "%s\n" % line.strip()
print(text)

对于结果,如果你想去掉空行:

print("Please enter 3 blank lines to terminate")
print("type your text here")
# declare variable to strore string
text = ""
stop_word = "quit"
counter = 0
while True:
    line = input()
    if line.strip() == '':
        counter += 1
        if counter == 3:
            # break terminates while loop
            break
        # continue go to start of while loop
        continue
    # \n is new line, %s is string formatting
    # str.strip() will remove any whitespace that is at start or end
    text += "%s\n" % line.strip()
print(text)

【讨论】:

  • 如何将其更改为 3 行,然后进入下一个代码?
  • 我还有一个问题,在行变量中,当用户进行输入时,它将包括不会引起任何事情的 3 行。无论如何要更改它而不更改输入字段中的 t 输入?
【解决方案2】:

您可以使用 sys.stdin.readlines 读取多行,并使用 ctrl + z(在 Windows 上)/ ctrl + d 中断。

import sys

msg = sys.stdin.readlines()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2021-04-05
    • 2016-12-13
    相关资源
    最近更新 更多