This:
print '{:x<4d}'.format(34)
prints this:
34xx
How can I do this:
width = 13
print '{:x<|width|d}'.format(34)
to get this:
34xxxxxxxxxxx
You can put one format field inside of the other:
>>> width = 13
>>> print '{:x<{}d}'.format(34, width)
34xxxxxxxxxxx
>>>
From the 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 theformat_spec
are substituted before theformat_spec
string is interpreted. This allows the formatting of a value to be dynamically specified.
Note however that the nesting can only go one level deep.
this will work:
>>> width = 13
>>> print '{:x<{}d}'.format(34,width)
34xxxxxxxxxxx
You can nest arguments in format, using kwargs allows you to be more explicit and less susceptible to confusing results:
fillchar = 'x'
width = 13
print "{:{f}<{w}d}".format(34, w=width, f=fillchar)