Chr*_*son 17 python formatting
是否可以在Python字符串格式化说明符中使用变量?
我试过了:
display_width = 50
print('\n{:^display_width}'.format('some text here'))
Run Code Online (Sandbox Code Playgroud)
但得到一个ValueError: Invalid format specifier.我也试过了display_width = str(50)
然而,只是进入print('\n{:^50}'.format('some text here'))工作就好了.
Bri*_*ell 22
是的,但你必须将它们作为参数传递给它们format,然后{}像参数名称本身一样引用它们:
print('\n{:^{display_width}}'.format('some text here', display_width=display_width))
Run Code Online (Sandbox Code Playgroud)
或者更短但更不明确:
print('\n{:^{}}'.format('some text here', display_width))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11523 次 |
| 最近记录: |