我正在寻找一个使用自定义占位符进行字符串格式化的 Python 库。我的意思是,我希望能够定义一个像 "%f %d %3c"
这样的字符串,例如 %f
将被替换为一些文件名,%d
带有目录名称,%3c
带有三位数的计数器。或者什么。它不必像 printf 那样,但如果是的话那就太好了。所以我希望能够定义每个字母的含义,是字符串还是数字,以及一些格式(如位数)数据。
这个想法是用户可以指定格式,然后我用数据填充它。就像 datefmt 一样。但对于定制的东西。
是否已经为Python(2.5+,遗憾的是没有为2.7和3及其__format__
)制作了类似的东西?
I am searching for a Python library for string formatting with custom placeholders. What I mean is that I would like to be able to define a string like "%f %d %3c"
where for example %f
would be then replaced with some filename, %d
with a directory name and %3c
with a counter with three digits. Or something. It does not have to be printf-like but it would be great if it would be. So I would like to be able to define what each letter means, is it string or number, and also some formatting (like number of digits) data.
The idea is that user can specify the format and I then fill it in with data. Like datefmt works. But for custom things.
Is there something like that already made for Python (2.5+, sadly not for 2.7 and 3 and its __format__
)?
发布评论
评论(1)
有
string.Template
,但它并没有完全提供您想要的内容:文档:http://docs.python.org/library/string.html#template-strings
但我认为这提供了您所需要的。只需指定一个模板字符串并使用它:
There is
string.Template
, but it doesn't provide exactly what you want:Documentation: http://docs.python.org/library/string.html#template-strings
But I think this provides what you need. Just specify a template string and use this: