Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何用单个字符/单词替换多个不同的单词?_Python_Python 3.x_String_Replace - Fatal编程技术网

在Python中,如何用单个字符/单词替换多个不同的单词?

在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)将多个字符替换为单个字

注意:无链接替换方法(或)在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"

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())

很好!比建立一个目标词列表和循环替换循环要干净得多。谢谢!