Python 如何根据字符串列表从字符串中删除子字符串

Python 如何根据字符串列表从字符串中删除子字符串,python,string,Python,String,我有一个字符串(颜色)列表,比如 我有一个字符串: sentence = "The jeans is chocolate brown in color and has brown colored pockets" 我必须从字符串中删除巧克力色和棕色。这只是一个例子。基本上,每当我在一个字符串中遇到一种颜色,如果它存在于颜色列表中,我就必须删除它。做这件事的有效方法是什么 我认为有一种方法是将字符串分为三元图、双元图和单元图。但是将这些n-gram连接起来并在所有n-gram之间保持一致将是一个

我有一个字符串(颜色)列表,比如

我有一个字符串:

sentence = "The jeans is chocolate brown in color and has brown colored pockets"
我必须从字符串中删除
巧克力色
棕色
。这只是一个例子。基本上,每当我在一个字符串中遇到一种颜色,如果它存在于颜色列表中,我就必须删除它。做这件事的有效方法是什么

我认为有一种方法是将字符串分为三元图、双元图和单元图。但是将这些n-gram连接起来并在所有n-gram之间保持一致将是一个问题

我原来的列表太大,字符串很短。我需要一个有效的解决方案,因为我必须循环列表中的所有元素。是否可以检查字符串中的颜色,然后检查该颜色是否在列表中。这不是一个有效的解决方案吗

l = ['chocolate brown','brown', 'chocolate']

sentence = "The jeans is chocolate brown in color and has brown colored pockets"

for word in l:
    # "word + ' '" is for deleting the trailing whitespace after each color word.
    sentence_new = sentence.replace(word + ' ', '') 
    sentence = sentence_new

print(sentence)
输出:

The jeans is in color and has colored pockets
基本上,只需将您不想要的替换为您想要的(我使用了一个空字符串“”),并将此操作放入循环中

请注意,
replace()
返回一个新字符串,而不是修改原始字符串,因此您必须将其放入一个新变量中,例如str_new。

您可以使用:


所以巧克力仍然在列表中?最后,字符串应该是“牛仔裤是彩色的,有彩色口袋”。
我必须从列表中删除巧克力棕色和棕色
与上面的注释完全不同。@wannaC,现在您有两个完全相反的语句,是来自列表还是字符串?@PadraicCunningham:我已经更新了我的问题。抱歉出错。@Akavall谢谢您的评论。我相应地修改了它。当我的列表很大而字符串很短时,这将是无效的。
The jeans is in color and has colored pockets
>>> import re
>>> l = ['chocolate brown','brown','chocolate']
>>> s = "The jeans is chocolate brown in color and has brown colored pockets"
>>>
>>> re.sub('|'.join(re.escape(r) for r in l), '', s)
'The jeans is  in color and has  colored pockets'