【问题标题】:python: how to delete blank lines? [duplicate]python:如何删除空行? [复制]
【发布时间】:2019-07-18 03:47:14
【问题描述】:

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

【问题讨论】:

  • 你能举个例子输入输出吗?
  • @Asif 我的问题解决了,还是谢谢你

标签: python string blank-line


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2015-11-16
    • 2015-07-15
    • 2011-06-18
    • 2018-12-20
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多