Christopher Pearson Christopher Pearson - 1 year ago 115
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 Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download