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

前端 未结 4 1558
天涯浪人
天涯浪人 2020-12-18 18:42

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

I have tried:

display_width = 50
print(\'\\n{:^display_width}\'.form         


        
4条回答
  •  失恋的感觉
    2020-12-18 19:18

    Python f-string is more flexible.

    >>> display_width = 50
    >>> display_content = "some text here"
    >>> print(f'\n{display_content:^{display_width}}')
    
                      some text here
    

提交回复
热议问题