将所有列表元素与一个字符串匹配,如果匹配则删除字符串部分

Match all the list elements with a string and removing the string parts if matched

import re    
my_list=['apple', 'oranges' , 'peaches']
string= ' \apples\ \cherries\ \bananas\ \peaches\ \avocado\ \oranges\ '
for x in my_list:
    replace=re.sub(x,' ',string)
    print(replace)

正确输出:- ' \cherries\ \bananas\ \avocado\ '

这段代码哪里出错了?

import re

a = ['apples', 'oranges' , 'peaches']
input_text = ' \apples\ \cherries\ \bananas\ \peaches\ \avocado\ \oranges\ '

output_text = re.sub(r'({})'.format('|'.join(['\\{}\\'.format(x) for x in a])), '', input_text)

output_text 是:

  \cherries\ \bananas\  \avocado\  

您可以使用 .replace(),它可能更容易:

my_list=['apples', 'oranges' , 'peaches'] # note typo in original post
string= r' \apples\ \cherries\ \bananas\ \peaches\ \avocado\ \oranges\ '

for item in my_list:
    thestring = '\' + item + '\ '
    string = string.replace(thestring, '')
print(string)

输出:

 \cherries\ \bananas\ \avocado\

但是,如果在最后一个反斜杠之后有可变数量的空格,您最好使用正则表达式并在搜索词末尾 ' ?'

无论哪种情况,print() 语句都应该在循环之外。