Christopher Pearson Christopher Pearson - 4 months ago 12
Python Question

How can you use a variable name inside a Python format specifier

Is it possible to use a variable inside of a Python string formatting specifier?

I have tried:

display_width = 50
print('\n{:^display_width}'.format('some text here'))


but get a
ValueError: Invalid format specifier
. I have also tried
display_width = str(50)


however, just entering
print('\n{:^50}'.format('some text here'))
works just fine.

Answer

Yes, but you have to pass them in as arguments to format, and then refer to them wrapped in {} like you would the argument name itself:

print('\n{:^{display_width}}'.format('some text here', display_width=display_width))

Or shorter but a little less explicit:

print('\n{:^{}}'.format('some text here', display_width))