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

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

I tried:

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

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

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

+6
source share
2 answers

Yes, but you must pass them as arguments to format , and then refer to them wrapped in {} , as well as the name of the argument itself:

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

Or shorter, but slightly less explicit:

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

Can

 print(('{0:^'+str(display_width)+'}').format('hello')) 
-1
source

Source: https://habr.com/ru/post/983778/


All Articles