python - 将所有列表元素与字符串匹配,如果匹配则删除字符串部分
问题描述
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\
推荐阅读
- javascript - 如何在本机基础的组件框之间创建空白
- rest - Rest API 的对应物
- excel - 将不同范围的单元格从 Excel 发送给不同的人
- javascript - 如何处理参数选项?
- reactjs - 为什么我的网站没有重定向到社交网站而是 mydomain/facebook?
- db2 - 从 BPM 升级到 BAW 之前的 DB2 数据库备份
- ios - Xcode LLDB 可以在 Swift 中观察 Object-C 变量吗?
- php - 限制对 WordPress 文件的直接访问
- python - Python socket.gaierror:[Errno 11001] getaddrinfo 失败
- python - Python pyautogui bot 工作一段时间后出现 TypeError: cannot unpack non-iterable NoneType object 解决方法