开发者

Python library for string formatting with custom placeholders

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 开发者_C百科something like that already made for Python (2.5+, sadly not for 2.7 and 3 and its __format__)?


There is string.Template, but it doesn't provide exactly what you want:

>>> 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'

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:

>>> 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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜