我有一个字符串,其中包含一些占位符,例如:
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'
关于python - 如何动态解析Python字符串模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527792/