简体   繁体   English

删除字符串中以某些字符开头的行

[英]Remove lines in a string that start with certain characters

I am trying to remove all lines in a string that start with some characters. 我试图删除以某些字符开头的字符串中的所有行。 I tried the block of code below but it was not working. 我尝试了下面的代码块,但无法正常工作。 My code should only print "Any thanks " as the result, but it outputs the entire original text. 我的代码只应打印"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)

Every string will fullify that or as those two conditions are mutually exclusive - compose your condition with and : 每个字符串都会充实该条件, or这两个条件是互斥的-使用and组合您的条件:

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

Your or statement is always returning True . 您的or语句始终返回True For example if the line starts with ' first_' then not line.startswith(' first_') returns False and not line.startswith(' last_') returns True so. 例如,如果该行以' first_' not line.startswith(' first_')开头,则not line.startswith(' last_') Falsenot line.startswith(' last_') True False or True evaluates to True . False or True计算结果为True

There are a couple ways you could write this, but the most straightforward would be to rewrite the if statement: 有两种写方法,但是最直接的方法是重写if语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM