使用自定义占位符进行字符串格式化的 Python 库

标签 python string-formatting string-interpolation

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

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

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

最佳答案

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'

关于使用自定义占位符进行字符串格式化的 Python 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050336/

相关文章:

string - 有没有办法防止字符串在 Swift 中被插入?

python - 循环数据时的高效 netCDF 分析

python - 使用 Ansible Python API,我如何才能访问我的代码中的任务级输出?

c# - 列字符串格式

python-3.x - 如何使用 configparser 插入节名称

python - 使用自定义占位符的高级 Python 字符串格式?

python - 避免 FOR 循环将多个字符串 append 到列表

python - 矩阵的 NumPy 张量/克罗内克积被打乱

swift - Kotlin 相当于 %@ 在 swift

c# - 字符串连接最佳实践