带自定义占位符的字符串格式化Python库

2 投票
1 回答
1980 浏览
提问于 2025-04-16 23:31

我在找一个Python库,用来格式化字符串,并且可以使用自定义的占位符。我的意思是,我想定义一个像 "%f %d %3c" 这样的字符串,比如说 %f 可以替换成某个文件名,%d 替换成一个目录名,而 %3c 则是一个三位数的计数器,类似这样的功能。虽然不一定要和printf一样,但如果能做到那样就更好了。我希望能定义每个字母的含义,比如它是字符串还是数字,还有一些格式设置(比如数字的位数)。

这个想法是用户可以指定格式,然后我再用数据填充进去。就像datefmt那样,但我想要的是自定义的东西。

有没有已经为Python(2.5以上,遗憾的是不支持2.7和3及其 __format__)做好的类似功能的库呢?

1 个回答

2

有一个叫做 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'

撰写回答