如何动态解析 python 字符串模板?

How to dynamically parse python string templates?

我有一个字符串,其中包含一些占位符,例如:

url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"

我无法使用模板 (http://is.gd/AKmGxa),因为我的占位符字符串需要通过某种逻辑来解释。

我需要遍历所有现有的占位符并将它们替换为代码生成的值。

我该怎么做? TIA!

使用 re.sub 可以接受替换函数作为第二个参数;

>>> url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
>>>
>>> def some_logic(match):
...     s = match.group()  # to get matched string
...     return str(len(s) - 1)  # put any login you want here
...
>>> import re
>>> re.sub('$\w+', some_logic, url)
'http://www.myserver.com/3/10/2'

顺便说一句,如果您通过自定义映射,也可以使用 string.Template

>>> class CustomMapping:
...     def __getitem__(self, key):
...         return str(len(key))
...
>>> import string
>>> url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
>>> string.Template(url).substitute(CustomMapping())
'http://www.myserver.com/3/10/2'