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

Pra*_*yan -1 python string replace python-3.x

注意:没有链接替换方法(或)循环 for 循环(或)列表推导中的字符

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

input_string.replace("the","").replace("was","").replace("is","").strip()
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

您可以使用 python regex module(re.sub) 用单个字符替换多个字符:

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

import re
re.sub("the|was|is","",input_string).strip()
Run Code Online (Sandbox Code Playgroud)

'字符需要替换为空格'