您不能更改
"".format()
,因为它是内置的,但如果可以向方法提供字符串和参数,则可以接受:
print(kf.format("{:t{}} {}", key, ':', value))
你可以通过子类化
string.Formatter
来允许空格式字段,并提供一个特殊的类型处理程序
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]
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
的值:
print(kf.format('{:t:<20} {}', k, v))
为了更好的可读性,但牺牲了一定的灵活性。
Python 3.4的字符串格式化程序的后移版本,包括对版本(至少)到3.5.0rc1的错误修复,包含此代码的现在可在
PyPI上获得。
print "{:<20} {}".format(key+':', value)
很好。 - martineau