gpt4 book ai didi

Python 字符串格式 : When to use ! s 转换标志

转载 作者:太空狗 更新时间:2023-10-29 17:22:47 24 4
gpt4 key购买 nike

Python 中这两个字符串格式语句有什么区别:

'{0}'.format(a)
'{0!s}'.format(a)

如果 a 是整数、列表或字典,则两者具有相同的输出。第一个 {0} 是否执行隐式 str() 调用?

Source

PS: 关键词:感叹号/bang "!s"格式

最佳答案

文档中提到:

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

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

可以举一个例子(再次来自 the documentation )来显示差异:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

关于Python 字符串格式 : When to use ! s 转换标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25441628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com