提示输入,直到给出2个空行

2024-06-16 13:04:34 发布

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

我需要提示用户输入,直到一行给出2个空行,请注意,为了清晰起见,输入读取可能有空行,我需要两个空行背对背地在它中断之前。在

到目前为止,我想出了一个办法:

def gather_intel():
    done = False
    while done is False:
        data = raw_input("Copy and paste the work log: ")
        if data is None:
            done = True

但是只要给出一个空行,这个过程就会结束,我还尝试向它添加另一个while循环:

^{pr2}$

然而,这是一个无限循环,永远不会结束。我怎样才能提示用户输入,直到有两个空行背对背地输入?在


Tags: 用户falseinputdatarawisdefcopy
2条回答

为了将来的我或者其他人。input到2个强制换行字符:

def handy_input(prompt='> '):
    'An `input` with 2 newline characters ending.'

    all_input_strings = ''

    # prompt the user for input
    given_input = input(prompt)
    all_input_strings += given_input
    # and handle the two newline ending                                                                                                           
    while given_input:
        # if previous input is not empty prompt again
        given_input = input('')
        all_input_strings += '\n' + given_input

    return all_input_strings

问题的答案有两行:

^{pr2}$
number_of_empty_responses = 0
while True:
    data = raw_input("Copy and paste the work log: ")
    if data == "":
        number_of_empty_responses += 1
        if number_of_empty_responses == 2:
            break
    else:
        number_of_empty_responses = 0
        pass # Received data, perform work.

相关问题 更多 >