概述
Is it possible to use a variable inside of a Python string formatting specifier?
I have tried:
display_width = 50
print('n{:^display_width}'.format('some text here'))
but get a ValueError: Invalid format specifier. I have also tried display_width = str(50)
however, just entering print('n{:^50}'.format('some text here')) works just fine.
解决方案
Yes, but you have to pass them in as arguments to format, and then refer to them wrapped in {} like you would the argument name itself:
print('n{:^{display_width}}'.format('some text here', display_width=display_width))
Or shorter but a little less explicit:
print('n{:^{}}'.format('some text here', display_width))
最后
以上就是专注雪糕为你收集整理的python变量名怎么写_如何在Python格式说明符中使用变量名称的全部内容,希望文章能够帮你解决python变量名怎么写_如何在Python格式说明符中使用变量名称所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复