是否可以在Python字符串格式说明符中使用变量?
我试过了:
display_width = 50
print('\n{:^display_width}'.format('some text here'))
但获得ValueError: Invalid format specifier
。我也试过display_width = str(50)
然而,只需输入print('\n{:^50}'.format('some text here'))
即可。
答案 0 :(得分:17)
是的,但你必须将它们作为参数传递给format
,然后引用它们包含在{}
中,就像参数名称本身一样:
print('\n{:^{display_width}}'.format('some text here', display_width=display_width))
或更短但有点不那么明确:
print('\n{:^{}}'.format('some text here', display_width))
答案 1 :(得分:0)
自从这个问题首次发布以来,python就引入了f字符串。有关信息,请参见this web page。
>>> 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.
答案 2 :(得分:0)
Python f字符串更灵活。
>>> display_width = 50
>>> display_content = "some text here"
>>> print(f'\n{display_content:^{display_width}}')
some text here
答案 3 :(得分:-2)
也许
print(('{0:^'+str(display_width)+'}').format('hello'))