python - 替换字符串中的多个值 - Python
问题描述
我有一个字符串 say'I have a string'
和一个 list ['I', 'string']
。如果我必须从给定字符串中删除列表中的所有元素,则正确的 for 循环可以正常工作。但是当我尝试使用列表理解时,它没有按预期工作,而是返回一个列表。
my_string = 'I have a string'
replace_list = ['I', 'string']
for ele in replace_list:
my_string = my_string.replace(ele, '')
# results --> ' have a '
[my_string.replace(ele, '') for ele in replace_list]
# results --> [' have a string', 'I have a ']
有什么方法可以更有效地做到这一点吗?
解决方案
使用正则表达式:
import re
to_replace = ['I', 'string']
regex = re.compile('|'.join(to_replace))
re.sub(regex, '', my_string)
输出:
' have a '
或者,您可以使用reduce
:
from functools import reduce
def bound_replace(string, old):
return string.replace(old, '')
reduce(bound_replace, to_replace, my_string)
输出:
' have a '
推荐阅读
- node.js - 如何从这些输入中获取数据
- prestashop - 如何修复 ContextErrorException:警告:声明
- c# - C# 引用指针
- python - 如何在 CodeHS 8.4.12:图书馆员,第 2 部分中仅打印姓氏?
- azure - 如何使用 Docker-Compose 将多个 Web Api 容器部署到 Azure
- r - 从单个 XML 创建多个 XML2 过滤
- jquery - 转换对象数组以在javascript中进行排序?
- android - 收到远程通知时在后台运行该方法而不启动应用程序
- django - 如何从 Django 注释和 F 表达式返回小时或分钟
- json - 如何遍历 Django 中特定项目的 JSON 数据