是否可以在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字符串,这使您无需使用format
方法即可执行此操作,并且它使用范围内的变量,而不必将命名变量作为关键字参数传递:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句