用替代值替换Python字符串中的“tokens”
想象一下,有一个脚本接收一个字符串:
http://whatever.org/?title=@Title@¬e=@Note@
还有一组代币(tokens):
['arg:Title=SampleTitle', 'arg:Note=SampleNote']
我们想用最符合Python风格的方法,把这些代币插入到字符串中。根据上面的例子,最终应该得到:
http://whatever.org/?title=SampleTitle¬e=SampleNote
我考虑过以下几种方法:
遍历这个列表,对于每个字符串,分离出代币的名称,然后用正则表达式替换掉每个找到的
@TOKEN_NAME;使用某种模板机制(类似于Ruby中的
ERB.template)。
相关问题:
1 个回答
17
要使用Python的优雅解决方案,可以采用str.format的格式化字符串语法,具体可以参考这里:
>>> template = "http://whatever.org/?title={Title}¬e={Note}"
>>> template.format(Title="SampleTitle", Note="SampleNote")
'http://whatever.org/?title=SampleTitle¬e=SampleNote'
你还可以把一个包含命名参数的字典拆开使用:
>>> template.format(**{"Title": "SampleTitle", "Note": "SampleNote"})
'http://whatever.org/?title=SampleTitle¬e=SampleNote'
如果你对输入格式感到困惑,可以很容易地通过正则表达式切换到更有用的格式:
>>> import re
>>> s = "http://whatever.org/?title=@Title@¬e=@Note@"
>>> re.sub(r"@(\w+?)@", r"{\1}", s)
'http://whatever.org/?title={Title}¬e={Note}'
(正则表达式的解释可以在这里找到)
同时也可以把这些信息处理成一个字典:
>>> tokens = ['arg:Title=SampleTitle', 'arg:Note=SampleNote']
>>> dict(s[4:].split("=") for s in tokens)
{'Note': 'SampleNote', 'Title': 'SampleTitle'}