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

时间:2012-02-23 20:44:05

标签: python python-3.x

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

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

我确信一本字典会更有意义,但这个例子只是让你们尝试理解我想要做的事情。任何帮助将不胜感激!

我正在使用Python 3。

4 个答案:

答案 0 :(得分:6)

多次使用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)

答案 1 :(得分:1)

您可以创建字典

>>> char_replace = {"%":"pct" , "*":"star" , "&":"and"}
>>> st = 'Hello %*& World'
>>> for i,j in char_replace.items():
...                st = st.replace(i,j)
...
>>> st
'Hello pctstarand World'
>>>

出于好奇,我试图用time替换这里讨论的字符串字符的所有方法。万一你想知道哪个更好。

1st way

>>> setup= '''
... char_replace = {"%":"pct" , "*":"star" , "&":"and"}
... st = 'Hello %*& World'
... for i,j in char_replace.items():
...         st = st.replace(i,j)
... '''
>>> t = Timer(setup)
>>> t.timeit()
2.3223999026242836
>>>

2nd way

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

3rd way

>>> setup2 = '''
... string = 'Hello %*& World'
... repl = {'*': 'star', '%': 'pct', '&': 'and'}
... repl = str.maketrans(repl)
... string = string.translate(repl)
...
... '''
>>> t = Timer(setup2)
>>> t.timeit()
3.3588874718125226
>>>

答案 2 :(得分:0)

如果您有预定的需要替换的内容以及需要替换的内容,那么使用字典的好方法就是这样:

string = 'Hello %*& World'
replacements = {}
replacements['%'] = 'pct'
replacements['*'] = 'star'
replacements['&'] = 'and'
for key in replacements:
    string = string.replace(key,replacements[key])

答案 3 :(得分:0)

>>> s = 'Hello %*& World'
>>> translate_dict = {ord(key): value 
        for key, value in zip(['%','*','&'], ['pct','star','and'])}
>>> s.translate(translate_dict)
'Hello pctstarand World'