我有一个字符串说'I have a string'
和列表['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 '