我需要填写一个小字符串模板。我的要求如下:
- 占位符的格式必须为
$(...)
- 它必须支持对象的“点访问”,就像
str.format
那样,例如'hey {obj.name}'.format(obj=some_object)
- 每当在替换中找不到占位符时,我不希望它崩溃,但继续处理其余部分。
我认为模块string
中的Template
类可以解决这个问题:它满足第1点(占位符)和第3点(容错),但不幸的是它没有支持“点访问”。
>>> from string import Template
>>> t = Template('$(obj.get)')
>>> t.substitute(obj=dict)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Development\CDBServer_active\lib\string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
File "C:\Development\CDBServer_active\lib\string.py", line 169, in convert
self._invalid(mo)
File "C:\Development\CDBServer_active\lib\string.py", line 146, in _invalid
(lineno, colno))
ValueError: Invalid placeholder in string: line 1, col 1
有没有办法在没有第三方库或不编写我自己的代码的情况下做到这一点?
最佳答案
只翻译格式字符串?
def translate(fmt):
# escape their markers
fmt = fmt.replace('{', '{{').replace('}', '}}')
# translate our markers
fmt = re.sub(r'\$\((.+?)\)', r'{\1}', fmt)
# unescape out markers
fmt = fmt.replace('$$', '$')
return fmt
obj = lambda: this_is_a_hack
obj.it = 123
translate("$(testing.it)").format(testing=obj)
关于python - 使用自定义占位符、对象的点访问和容错来格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463581/