首页 > 解决方案 > 用列表替换多个字符串

问题描述

我正在尝试使用列表从单个文本字符串中删除多个项目。

这是解决方案的开始:

tmp_text = 'Mr. Random Name'
replace = ['Mr. ', 'Ms. ','Prof. ']
tmp_text = [tmp_text.replace(r, '') for r in replace]

但是,我想返回一个文本字符串,其中删除了列表“替换”中的所有项目。上面返回三个字符串:['Random Name', 'Mr. 随机名字','先生。随机名称']

标签: python-3.x

解决方案


在循环中替换:

for r in replace:
    tmp_text = tmp_text.replace(r, "")

或者使用正则表达式:

tmp_text = re.sub("|".join(replace), "", tmp_text)

推荐阅读