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

前端 未结 4 1564
天涯浪人
天涯浪人 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:19

    It seems like since this question was first posted, python introduced f-strings. See this web page for info.

    >>> name = 'Fred'
    >>> age = 42
    >>> f'He said his name is {name} and he is {age} years old.'
    He said his name is Fred and he is 42 years old.
    

提交回复
热议问题