python: 如何删除空行?

python: how to delete blank lines?

输入是为了包含用户的多行答案,开头的所有空格都需要删除,我用line.strip()记下来了。但是,我想不出一种方法来删除每行答案之间的输入空行。

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)

您可以通过检查行的值来检测代码中的空行。

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

以下代码丢弃空行:

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)