在Python中,如何用单个字符/单词替换多个不同的单词?
注意:无链接替换方法(或)在for循环(或)列表理解中循环字符在Python中,如何用单个字符/单词替换多个不同的单词?,python,python-3.x,string,replace,Python,Python 3.x,String,Replace,注意:无链接替换方法(或)在for循环(或)列表理解中循环字符 input_string = "the was is characters needs to replaced by empty spaces" input_string.replace("the","").replace("was","").replace("is","").strip() 输出:“需要用空格替换字符” 有什么直接的方法可以做到这一点吗?您可以使用python正则表达式模块(re.sub)将多个字符替换为单个字
input_string = "the was is characters needs to replaced by empty spaces"
input_string.replace("the","").replace("was","").replace("is","").strip()
输出:“需要用空格替换字符”
有什么直接的方法可以做到这一点吗?您可以使用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()
“字符需要用空格替换”这应该会有帮助
input_string = "the was is characters needs to replaced by empty spaces"
words_to_replace=['the', 'was','is']
print(input_string)
for words in words_to_replace:
input_string = input_string.replace(words, "")
print(input_string.strip())
很好!比建立一个目标词列表和循环替换循环要干净得多。谢谢!