想象一个接收字符串的脚本:
http://whatever.org/?title=@Title@¬e=@Note@
...和 token 列表:
['arg:Title=SampleTitle', 'arg:Note=SampleNote']
将这些标记插入字符串的最 Pythonic 方法是什么,以便使用上面的示例生成以下内容:
http://whatever.org/?title=SampleTitle¬e=SampleNote
我考虑过:
遍历列表,对于它包含的每个字符串,拆分出 token 名称,并对找到的每个
@TOKEN_NAME
实例进行正则表达式替换;和使用某种模板机制(类似于用 Ruby 的
ERB.template
可以做的事情)。
最佳答案
要使用 Pythonic 解决方案,请采用 str.format
format string syntax 的规范:
>>> 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'
如果您受困于您的输入格式,您可以使用 regular expression 轻松切换到更有用的格式:
>>> import re
>>> s = "http://whatever.org/?title=@Title@¬e=@Note@"
>>> re.sub(r"@(\w+?)@", r"{\1}", s)
'http://whatever.org/?title={Title}¬e={Note}'
(参见正则表达式解释 here)
并将标记也处理成字典:
>>> tokens = ['arg:Title=SampleTitle', 'arg:Note=SampleNote']
>>> dict(s[4:].split("=") for s in tokens)
{'Note': 'SampleNote', 'Title': 'SampleTitle'}
关于python - 用备用值替换 Python 字符串中的 "tokens",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668282/