前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于python中format占位符中的 {!} 参数[通俗易懂]

关于python中format占位符中的 {!} 参数[通俗易懂]

作者头像
全栈程序员站长
发布2022-09-07 20:15:03
1.8K0
发布2022-09-07 20:15:03
举报

大家好,又见面了,我是你们的朋友全栈君。

在看celery的时候,发现里面有这么一句

代码语言:javascript
复制
print('Request: {0!r}'.format(self.request))

关于里面的{0!r}是什么意思翻了一下文档。

文档里是这么描述的

代码语言:javascript
复制
replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"

------

Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().

Some examples:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first

是说感叹号后面跟的是conversion,而conversion有两个值.

分别是s对应str()函数, r对应repr()函数。

因此上面的翻译一下类似于下面

代码语言:javascript
复制
"Harold's a clever {0!s}" == "Harold's a clever str({0})"

"Bring out the holy {name!r}" == "Bring out the holy repr({name})"

实际调用时的写法应该是

代码语言:javascript
复制
"Harold's a clever {0!s}".format(string) == "Harold's a clever {0}".format(str(string))

"Bring out the holy {name!r}".format(string) == "Bring out the holy {name}".format(repr(string))

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/156110.html原文链接:https://javaforall.cn

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com