【问题标题】:Python library for string formatting with custom placeholders用于使用自定义占位符进行字符串格式化的 Python 库
【发布时间】:2011-10-26 09:25:21
【问题描述】:

我正在寻找一个 Python 库,用于使用自定义占位符进行字符串格式化。我的意思是我希望能够定义一个像"%f %d %3c" 这样的字符串,例如%f 将被替换为一些文件名,%d 具有目录名称,%3c 具有三个数字的计数器.或者其他的东西。它不必是类似 printf 的,但如果可以的话,那就太好了。所以我希望能够定义每个字母的含义,是字符串还是数字,以及一些格式(如位数)数据。

这个想法是用户可以指定格式,然后我用数据填充它。就像 datefmt 一样。但是对于定制的东西。

是否已经为 Python(2.5+,遗憾的是不是为 2.7 和 3 及其__format__)制作了类似的东西?

【问题讨论】:

    标签: python string-formatting string-interpolation


    【解决方案1】:

    string.Template,但它并没有提供你想要的:

    >>> from string import Template
    >>> t = Template("$filename $directory $counter")
    >>> t.substitute(filename="file.py", directory="/home", counter=42)
    'file.py /home 42'
    >>> t.substitute(filename="file2.conf", directory="/etc", counter=8)
    'file2.conf /etc 8'
    

    文档:http://docs.python.org/library/string.html#template-strings

    但我认为这可以满足您的需求。只需指定一个模板字符串并使用它:

    >>> template = "%(filename)s %(directory)s %(counter)03d"
    >>> template % {"filename": "file", "directory": "dir", "counter": 42}
    'file dir 042'
    >>> template % {"filename": "file2", "directory": "dir2", "counter": 5}
    'file2 dir2 005'
    

    【讨论】:

    • 哦,我忘了这个。但是让用户指定格式化字符串是安全的吗?或者这会导致一些漏洞利用吗?
    • 只要您不将locals() 作为格式化参数,他就只能访问您提供的字典。
    • 我会小心暴露完整的格式化功能——想想这样的事情: "%030000000000000d" % (3) 这需要提前分配一大块内存。这里可能还有很多其他可能的漏洞......
    猜你喜欢
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多