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

时间:2016-12-07 20:07:33

标签: python python-2.7 input

我需要提示用户输入,直到连续给出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循环:

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

然而,这是一个无限循环,永远不会结束。如何提示用户输入,直到输入背后有两个空白行?

2 个答案:

答案 0 :(得分:2)

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.

答案 1 :(得分:0)

为了将来我或其他人。 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

问题的答案用两行空行表示:

def empty_lines_input(prompt='> ', n_lines=2):
    'An `input` with `n_lines` empty line 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 n_lines>0:
        # if previous input is not empty prompt again
        given_input = input('')
        all_input_strings += '\n' + given_input
        # check if it was an empty line
        if not given_input:
            n_lines -= 1
        else:
            n_lines = 2

    return all_input_strings