2

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

4 Answers 4

2

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 the format_spec are substituted before the format_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.

1
  • Thank you. Just what I wanted.
    – Sam R.
    Commented Apr 8, 2015 at 3:57
1

This works

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

this will work:

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

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)
1
  • Awesome. Thanks a lot. Using named params are really good here.
    – Sam R.
    Commented Apr 8, 2015 at 3:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.