问题描述
使用 Python 的字符串格式,是否有一种很好的方法可以为填充为固定大小的左对齐字符串添加后缀?
Using Pythons string formatting, is there a nice way to add a suffix to a left aligned string that is padded to a fixed size?
我想按以下格式打印键值对列表:
I want to print a list of key-value-pairs in the following formatting:
a_key: 23
another_key: 42
...
问题是':'.到目前为止,我发现的最佳解决方案是将 ':' 附加到键名:
The problem is the ':'. The best solution I found so far is to append the ':' to the key name:
print "{:<20} {}".format(key+':', value)
但我认为这是一个相当丑陋的解决方案,因为它减少了格式和值的分离.是否可以直接在格式规范中实现?
But I think this is a rather ugly solution, as it diminishes the separation of formatting and values. Is it possible to achieve this directly in the format specification?
我正在寻找的是这样的:
What I am looking for is something like this:
print "{do something here} {}".format(key, value)
推荐答案
您不能更改 "".format()
因为它是内置的,但如果提供字符串和方法的参数:
You cannot change "".format()
as it is a built-in but if it is acceptable to provide the string and parameters to a method:
print(kf.format("{:t{}} {}", key, ':', value))
您可以通过子类化 string.Formatter
以允许空格式字段并提供特殊类型处理程序 t
来实现:
you can do so by subclassing string.Formatter
to allow empty format fields and provide a special type handler t
:
from string import Formatter
import sys
if sys.version_info < (3,):
int_type = (int, long)
else:
int_type = (int)
class TrailingFormatter(Formatter):
def vformat(self, *args):
self._automatic = None
return super(TrailingFormatter, self).vformat(*args)
def get_value(self, key, args, kwargs):
if key == '':
if self._automatic is None:
self._automatic = 0
elif self._automatic == -1:
raise ValueError("cannot switch from manual field specification "
"to automatic field numbering")
key = self._automatic
self._automatic += 1
elif isinstance(key, int_type):
if self._automatic is None:
self._automatic = -1
elif self._automatic != -1:
raise ValueError("cannot switch from automatic field numbering "
"to manual field specification")
return super(TrailingFormatter, self).get_value(key, args, kwargs)
def format_field(self, value, spec):
if len(spec) > 1 and spec[0] == 't':
value = str(value) + spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)
kf = TrailingFormatter()
w = 20
ch = ':'
x = dict(a_key=23, another_key=42)
for k in sorted(x):
v = x[k]
print(kf.format('{:t{}<{}} {}', k, ch, w, v))
给你:
a_key: 23
another_key: 42
您当然可以对 ch
和 w
值进行硬编码:
You can of course hardcode the ch
, and w
values:
print(kf.format('{:t:<20} {}', k, v))
可读性更好,但灵活性较差.
for better readability, but less flexibility.
Python 3.4 string.Formatter() 的后向移植,其中包括(至少)高达 3.5.0rc1 的版本的错误修复,其中包括此代码现在可在 PyPI
A backport of the Python 3.4 string.Formatter() that includes a bugfix for versions (at least) up to 3.5.0rc1, that includes this code is now available on PyPI
这篇关于打印字符串左对齐固定宽度和后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!