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

标签 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'

关于python - 如何动态解析Python字符串模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527792/

相关文章:

python - 突出显示时如何删除文本现有的背景颜色?

python - 有效求和一维 NumPy 数组的外积

c++ - Clang (OS X) 在特定的嵌套声明中需要 "template"关键字,而 VS 禁止它

c++ - 如何确定迭代器在 C++ 模板函数中指向的对象的类型?

c++ - 使用 SFINAE 选择 friend 或基类 c++x03

Python:如何通过派生类实例访问父类对象?

python - 将表示为 numpy ndarray 的彩色图像更改为灰度

c++ - 将 std::string 转换为 LPCSTR 时的奇怪行为

c - 我似乎不知道如何使用 strcat 连接两个 char 指针字符串,这不正确吗?

java - 通过正则表达式对 and , !, ),(, | 等运算符进行字符串验证