【问题标题】:Remove lines in a string that start with certain characters删除字符串中以某些字符开头的行
【发布时间】:2019-07-23 01:23:24
【问题描述】:

我正在尝试删除以某些字符开头的字符串中的所有行。我尝试了下面的代码块,但它不起作用。我的代码应该只打印"Any thanks" 作为结果,但它会输出整个原始文本。

text = """Any thanks \n first_************ \n last_************ has \n"""

from io import StringIO
s = StringIO(text)
for line in (s):
    if not line.startswith(' first_') \
        or not line.startswith(' last_'):
        print(line)

【问题讨论】:

    标签: python python-3.x string text nlp


    【解决方案1】:

    每个字符串都将满足 or,因为这两个条件是互斥的 - 用 and 组合你的条件:

    if not line.startswith(' first_') \
        and not line.startswith(' last_'):
    

    【讨论】:

      【解决方案2】:

      您的or 语句总是返回True。例如,如果行以' first_' 开头,那么not line.startswith(' first_') 返回Falsenot line.startswith(' last_') 返回True,所以。 False or True 计算结果为 True

      您可以通过多种方式编写此代码,但最直接的方式是重写 if 语句:

      for line in (s):
          if not (line.startswith(' first_') or line.startswith(' last_')):
              print(line)
      

      【讨论】:

        猜你喜欢
        • 2019-11-15
        • 2017-09-27
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 2010-12-16
        • 2019-08-11
        • 1970-01-01
        • 2014-12-02
        相关资源
        最近更新 更多