首页 > 解决方案 > 如何在 Python 中用单个字符/单词替换多个不同的单词?

问题描述

注意:不使用链接替换方法(或)循环 for 循环(或)列表理解中的字符

input_string = "the was is characters needs to replaced by empty spaces"

input_string.replace("the","").replace("was","").replace("is","").strip()

输出:'字符需要替换为空格'

有没有直接的方法可以做到这一点?

标签: pythonpython-3.xstringreplace

解决方案


您可以使用 python 正则表达式模块(re.sub)用单个字符替换多个字符:

input_string = "the was is characters needs to replaced by empty spaces"

import re
re.sub("the|was|is","",input_string).strip()

'字符需要替换为空格'


推荐阅读