簡體   English   中英

如何從括號中刪除字符串,包括帶有條件的括號?

[英]How to remove a string from brackets including the brackets with a condition?

我有一個與此類似的問題。

我想刪除括號和其中的文字,但保留一些文字。 例如我有一個列表:

["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]

我想保留(#)(##) ,但刪除(maybe)(mall)

預期輸出:

["Going", "(#)", "to", "the", "(##)", "market"]

列表中可以有任意數量的帶括號的單詞,例如'maybe''mall'

#的括號最多可以有 3 個哈希。

您可以使用列表理解來使用正則表達式過濾原始列表:

import re

a = ["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]
b = [word for word in a if re.match(r"[^(]|\(#{1,3}\)", word)]

給出:

['Going', '(#)', 'to', 'the', '(##)', 'market']

re.match匹配字符串開頭的模式。 圖案的意思是:

  • [^(] -(之外的任何字符。
  • | - 或者...
    • \( - 文字括號
    • #{1,3} - 1 到 3 次重復#
    • \) - 文字括號

正則表達式演示

以一種通用的方式,您可以解析列表並評估該單詞是否有一對括號。 如果是這樣,並且里面的單詞不是#、## 或 ### ,那么您應該將其從輸出中排除。 假設您有一個字符串列表:

a = ['Going', '(#)', '(maybe)', 'to', 'the', '(##)', '(mall)', 'market']

output = [word for word in a if ('(' not in word and ')' not in word) or word.strip('()') in ['#', '##', '###']]
print(output)
# ['Going', '(#)', 'to', 'the', '(##)', 'market']

strip方法只保留給定參數中的字符串(在本例中為() )。

您可以在此處了解有關列表推導的更多信息:https ://www.w3schools.com/python/python_lists_comprehension.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM