python - 使用 !s 与 :s to format a string in Python

标签 python string python-3.x string-formatting

我真的很好奇 Python 3 中的 :s 格式字符串。The documentation!sconversion:sformat_spec

它还说 !s 将应用 str(),但它没有说任何关于 :s 的类似内容。我认为它们之间没有显着差异,但我想确定一下。谁能澄清这些?

一些代码示例:

print("{!s}".format("this"))
print("{:s}".format("that"))
# I want to be sure that these two are processed identically internally

这仍然令人困惑,但让我用我自己(外行)的话来总结一下。

  1. type("whatever".format) 总是 str
  2. 如果您想在格式化之前将对象转换为 str,请使用 !s
  3. :s 表示对象(或转换后的对象)在某些内部格式化过程中将被视为 str。这是默认的 format_spec

这里有什么问题吗?

最佳答案

!s 及其兄弟 !a!r 应用 str() ascii()repr() 分别是 before 插值和格式化。这些称为转换标志,是Format String Syntax spec 的一部分。 ,而不是 per-field formatting spec插值时应用于值:

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.

我的大胆强调。

:s 仅适用于转换结果之后(如果未应用转换,则为原始对象),并且仅适用于对象类型的 __format__ 方法支持该格式选项。通常,只有 str 类型的对象支持这个格式化程序;它是默认的,主要是因为 Format Specification Mini-Language允许存在类型字符,并且因为较旧的 % printf-style formatting具有 %s 格式。如果您尝试将 s 类型应用于不支持它的对象,则会出现异常。

当您的对象本身不是字符串并且两者都不是时,请使用 !s(或 !a!r) t 支持其他格式(并非所有类型都支持)或格式不同于它们的 str()ascii()repr() 转换:

>>> class Foo:
...     def __str__(self):
...         return "Foo as a string"
...     def __repr__(self):
...         return "<Foo as repr, with åéæ some non-ASCII>"
...     def __format__(self, spec):
...         return "Foo formatted to {!r} spec".format(spec)
...
>>> print("""\
... Different conversions applied:
... !s: {0!s:>60s}
... !r: {0!r:>60s}
... !a: {0!a:>60s}
... No conversions: {0:>50s}
... """.format(Foo()))
Different conversions applied:
!s:                                    Foo as a string
!r:             <Foo as repr, with åéæ some non-ASCII>
!a:    <Foo as repr, with \xe5\xe9\xe6 some non-ASCII>
No conversions: Foo formatted to '>50s' spec

注意:所有格式规范指定的格式是__format__方法的责任;最后一行不应用 >50s 格式化规范中的对齐操作,Foo.__format__ 方法仅将其用作格式化操作中的文字文本(使用 !r 转换在这里)。

另一方面,对于转换后的值,使用 str.__format__ 方法,输出在 50 个字符宽的字段中向右对齐,左侧用空格填充。

关于python - 使用 !s 与 :s to format a string in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41630728/

相关文章:

java - 我的 while 循环第二次显示两个打印时遇到问题

python - 如何拆分字典中的列表以创建一个新列表?

Python 3 - 计算两个时间值之间的差异

python-3.x - 如何通过 pandas `df.to_sql()` 在已创建的数据库表中插入值

python - 在 Mac OS 上安装 pip 错误 - 权限被拒绝 : '/Library/Python/2.7/site-packages/pip'

python - 如何在rabbitmq、pika python中优雅地暂停和恢复消费

Python 脚本不在 cron 下运行,尽管在手动运行时工作

python - 使用 python 3 抓取 Json

c - C 中的 char 指针数组 - 区分空元素

java - 创建字符串对象以连接结果