我是靠谱客的博主 专注雪糕,这篇文章主要介绍python变量名怎么写_如何在Python格式说明符中使用变量名称,现在分享给大家,希望可以做个参考。

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格式说明符中使用变量名称内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(70)

评论列表共有 0 条评论

立即
投稿
返回
顶部