首页 > 解决方案 > 替换字符串中的多个值 - 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 ']

有什么方法可以更有效地做到这一点吗?

标签: pythonstringreplace

解决方案


使用正则表达式:

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 '

推荐阅读