[英]Remove lines in a string that start with certain characters
我試圖刪除以某些字符開頭的字符串中的所有行。 我嘗試了下面的代碼塊,但無法正常工作。 我的代碼只應打印"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)
每個字符串都會充實該條件, or
這兩個條件是互斥的-使用and
組合您的條件:
if not line.startswith(' first_') \
and not line.startswith(' last_'):
您的or
語句始終返回True
。 例如,如果該行以' first_'
not line.startswith(' first_')
開頭,則not line.startswith(' last_')
False
, not line.startswith(' last_')
True
。 False or True
計算結果為True
。
有兩種寫方法,但是最直接的方法是重寫if語句:
for line in (s):
if not (line.startswith(' first_') or line.startswith(' last_')):
print(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.