字符串替换使用字典

akh*_*khi 5 python string replace string-formatting

我正在学习python并在字符串上工作,以便使用字典找到更好的字符串替换方法

我有一个字符串,其中包含我的自定义占位符,如下所示:

placeholder_prefix = '$['
placeholder_suffix = ']'

dict={'key1':'string','key2':placeholders}
msg='This $[key1] contains custom $[key2]'
Run Code Online (Sandbox Code Playgroud)

我希望占位符('prefix-suffix'和'keys')应该被字典中的'value'替换,如下所示:

' 此字符串包含自定义占位符'

我可以通过编写函数获取消息:'This [string]包含自定义[placeholders]':

def replace_all(text):
    for key, value in brand_dictionary.iteritems():
        text = text.replace(key, value).replace('$[', '[')        
    return text
Run Code Online (Sandbox Code Playgroud)

我可以尝试使用不同的替换来删除'$ ['和']',但这可以替换作为消息本身的一部分包含的任何字符(如'$','[',']')(不作为占位符的一部分).所以我想避免这种情况,只替换自定义占位符.

我可以想到正则表达式(对于占位符),但由于我的消息包含多个键,所以它似乎没有用处?

有没有更好的方法在python中做到这一点?

Kas*_*mvd 2

作为更通用的方法,您可以使用re.sub适当的替换功能:

>>> d={'key1':'string','key2':'placeholders'}
>>> re.sub(r'\$\[([^\]]*)\]',lambda x:d.get(x.group(1)),msg)
'This string contains custom placeholders'
Run Code Online (Sandbox Code Playgroud)

使用正则表达式的优点是它拒绝匹配字符串中不具有预期格式的占位符字符!

或者作为一种更简单的方法,您可以使用字符串格式,如下所示:

In [123]: d={'key1':'string','key2':'placeholders'}
     ...: msg='This {key1} contains custom {key2}'
     ...: 
     ...: 

In [124]: msg.format(**d)
Out[124]: 'This string contains custom placeholders'
Run Code Online (Sandbox Code Playgroud)

或者,如果变量数量不是很大,则可以将键作为可在当前命名空间中访问的变量,而不是使用字典,然后使用f-strings自 Python-3.6 以来引入的功能:

In [125]: key1='string'
     ...: key2= 'placeholders'
     ...: msg=f'This {key1} contains custom {key2}'
     ...: 

In [126]: msg
Out[126]: 'This string contains custom placeholders'
Run Code Online (Sandbox Code Playgroud)