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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Just what I wanted.
1

This works

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

Comments

1

this will work:

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

Comments

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 Comment

Awesome. Thanks a lot. Using named params are really good here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.