Python:如何删除空白行?

时间:2019-07-18 03:47:14

标签: python string blank-line

输入被设计为包含来自用户的多行答案,所有开头的空白都需要删除,我使用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)

1 个答案:

答案 0 :(得分:1)

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

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)