Skip to main content
 首页 » 编程设计

python之用 Python 3 中的列表或字典中的内容替换字符串的内容

2025年05月04日15mate10pro

我正在尝试将 string.replace() 与我希望查找和替换的指定内容列表一起使用:

string = 'Hello %*& World' 
string.replace(['%','*','&'], ['pct','star','and']) 

我相信字典会更有意义,但这个例子只是为了让你们尝试理解我正在尝试做的事情。任何帮助将不胜感激!

我正在使用 Python 3。

请您参考如下方法:

只需多次使用str.replace...

string = 'Hello %*& World' 
repl = ['%','*','&'], ['pct','star','and'] 
for a, b in zip(*repl): 
    string = string.replace(a, b) 

但是,这种存储替换的方式看起来不太好。一种可能是使用字典:

repl = {'*': 'star', '%': 'pct', '&': 'and'} 
for a, b in repl.items(): 
    string = string.replace(a, b) 

此外,如果您知道要替换的字符串总是只有一个字符,str.translate 会更有效率。像这样使用它:

repl = {'*': 'star', '%': 'pct', '&': 'and'} 
repl = str.maketrans(repl) 
string = string.translate(repl)