Search code examples
pythonstringblank-line

python: how to delete blank lines?


The input is designed to contain multiple lines of answer from the user, all the white spaces at the start need to be deleted, I have down that by using line.strip(). However, I cannot figure out a way to delete the input blank lines between each line of the answer.

print("after press enter and add a quit at end of your code")
print("copy and paste your code here")
text = ""
stop_word = "end"
while True:
    line = input()
    if line.strip() == stop_word:
        break
    text += "%s\n" % line.strip()
print(text)

Solution

  • You can detect a blank line in your code by checking the value of the line.

    if line == "":
        # start the next iteration without finishing this one
        continue
    

    The following code discards a line if it is empty:

    print("after press enter and add a quit at end of your code")
    print("copy and paste your code here")
    text = ""
    stop_word = "end"
    while True:
        line = input()
        if line == "":
            continue
    
        if line.strip() == stop_word:
            break
        text += "%s\n" % line.strip()
    print(text)