python - 用备用值替换 Python 字符串中的 "tokens"

标签 python python-2.7 interpolation

想象一个接收字符串的脚本:

http://whatever.org/?title=@Title@¬e=@Note@

...和 token 列表:

['arg:Title=SampleTitle', 'arg:Note=SampleNote']

将这些标记插入字符串的最 Pythonic 方法是什么,以便使用上面的示例生成以下内容:

http://whatever.org/?title=SampleTitle¬e=SampleNote

我考虑过:

  1. 遍历列表,对于它包含的每个字符串,拆分出 token 名称,并对找到的每个 @TOKEN_NAME 实例进行正则表达式替换;和

  2. 使用某种模板机制(类似于用 Ruby 的 ERB.template 可以做的事情)。

最佳答案

要使用 Pythonic 解决方案,请采用 str.format format string syntax 的规范:

>>> template = "http://whatever.org/?title={Title}&note={Note}"
>>> template.format(Title="SampleTitle", Note="SampleNote")
'http://whatever.org/?title=SampleTitle&note=SampleNote'

您还可以解压命名参数的字典:

>>> template.format(**{"Title": "SampleTitle", "Note": "SampleNote"})
'http://whatever.org/?title=SampleTitle&note=SampleNote'

如果您受困于您的输入格式,您可以使用 regular expression 轻松切换到更有用的格式:

>>> import re
>>> s = "http://whatever.org/?title=@Title@&note=@Note@"
>>> re.sub(r"@(\w+?)@", r"{\1}", s)
'http://whatever.org/?title={Title}&note={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/

相关文章:

python - 属性错误 : 'QWheelEvent' object has no attribute 'delta'

python - 在具有循环节点的复杂数据结构中寻找最短路径

python - sklearn "transport"训练模型的最佳实践

python - 如何编写多个整数数组的测试?

python - QuickFix pip 安装

python - 如何在 PyQt4 中选择性地设置文本的前景色

python-2.7 - 修复 Anaconda 中的 matplotlib/numpy 依赖 hell

java - 从三点定义曲线

Matlab插值(interpn)忽略带NaN的维度

opengl - 在OpenGL中绘制Hermite曲线