首页 > 解决方案 > 将所有列表元素与字符串匹配,如果匹配则删除字符串部分

问题描述

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\'

这段代码我哪里出错了?

标签: pythonpython-3.xstringlistre

解决方案


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\  

推荐阅读