是否可以在 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'))
就可以了。
最佳答案
是的,但您必须将它们作为参数传递给 format
,然后像使用参数名称本身一样引用包裹在 {}
中的它们:
print('\n{:^{display_width}}'.format('some text here', display_width=display_width))
或者更短但不那么明确:
print('\n{:^{}}'.format('some text here', display_width))
自从这个问题最初发布以来,Python 3.6 添加了 f-strings,它允许您在不使用 format
方法的情况下执行此操作,并且它使用范围内的变量而不是必须传入命名变量作为关键字参数:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
https://stackoverflow.com/questions/29044940/