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

发布于 2024-11-29 04:32:45 字数 371 浏览 6 评论 0 原文

我正在寻找一个使用自定义占位符进行字符串格式化的 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__)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一绘本一梦想 2024-12-06 04:32:45

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'

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文