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

关于python中format占位符中的 {!} 参数[通俗易懂]在看 celery 的时候 发现里面有这么一句 print Request 0 r format self request 关于里面的 0 r 是什么意思翻了一下文档 文档里是这么描述的 replacement field field name conversion format spec Two

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

print('Request: {0!r}'.format(self.request))

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

文档里是这么描述的

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()函数。

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

"Harold's a clever {0!s}" == "Harold's a clever str({0})"

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

实际调用时的写法应该是

"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))
编程小号
上一篇 2025-07-01 09:57
下一篇 2025-02-26 14:27

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/142096.html