python - 使用自定义占位符、对象的点访问和容错来格式化字符串

标签 python string templates

我需要填写一个小字符串模板。我的要求如下:

  • 占位符的格式必须为 $(...)
  • 它必须支持对象的“点访问”,就像 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/

相关文章:

python - 为什么我的 Flask 网站没有运行 CSS 文件?

python - 多处理:池和映射以及 sys.exit()

string - 为什么用彩色 crate 中的彩色字符串替换子字符串不起作用?

node.js - Sendgrid 中的替代代币列表

c++ - 在赋值中折叠表达式

c++ - 为什么模板只能在头文件中实现?

python - 在 numpy 2D 矩阵中计算 "holes"

python - 我正在获取 AttributeError : 'list' object has no attribute 'lower' while trying to split ("") on text data

.NET System::String 到存储在 char* 中的 UTF8 字节

string - NSString 不能隐式转换为 String - 但一切都是 NSString