在格式字符串中使用参数

Use parameter in format string

这个:

print '{:x<4d}'.format(34)

打印这个:

34xx

我该怎么做:

width = 13
print '{:x<|width|d}'.format(34)

得到这个:

34xxxxxxxxxxx

这个有效

('{:x<%dd}' % width).format(34)

您可以将一个格式字段放在另一个格式字段中:

>>> width = 13
>>> print '{:x<{}d}'.format(34, width)
34xxxxxxxxxxx
>>>

来自docs

A format_spec field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

但是请注意,嵌套只能深入一层。

这会起作用:

>>> width = 13 
>>> print '{:x<{}d}'.format(34,width)
34xxxxxxxxxxx

您可以在格式中嵌套参数,使用 kwargs 可以让您更加明确并且不易混淆结果:

fillchar = 'x'
width = 13
print "{:{f}<{w}d}".format(34, w=width, f=fillchar)