Python 字符串格式:何时使用 !s 转换标志 [英] Python string format: When to use !s conversion flag

查看:28
本文介绍了Python 字符串格式:何时使用 !s 转换标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

来源

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

解决方案

文档中提到:

<块引用>

转换字段在格式化之前会导致类型强制.通常,格式化值的工作由 __format__() 完成值本身的方法.但是,在某些情况下需要强制将类型格式化为字符串,覆盖其自身格式定义.通过将值转换为字符串之前调用__format__(),绕过正常的格式化逻辑.

当前支持两个转换标志:'!s',它调用str() 在值上,'!r' 调用 repr().

可以举一个例子(同样来自文档)来显示差异:

<预><代码>>>>"repr() 显示引号:{!r}; str() 不显示:{!s}".format('test1', 'test2')repr() 显示引号:'test1';str() 不显示:test2"

What's the difference between these 2 string format statements in Python:

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

Both have the same output if a is an integer, list or dictionary. Is the first one {0} doing an implicit str() call?

Source

PS: keywords: exclamation / bang "!s" formatting

解决方案

It is mentioned in the documentation:

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().

An example can be taken (again from the documentation) to show the difference:

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

这篇关于Python 字符串格式:何时使用 !s 转换标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆