我真的很好奇 Python 3 中的 :s
格式字符串。The documentation说 !s
是 conversion 而 :s
是 format_spec
。
它还说 !s
将应用 str()
,但它没有说任何关于 :s
的类似内容。我认为它们之间没有显着差异,但我想确定一下。谁能澄清这些?
一些代码示例:
print("{!s}".format("this"))
print("{:s}".format("that"))
# I want to be sure that these two are processed identically internally
这仍然令人困惑,但让我用我自己(外行)的话来总结一下。
type("whatever".format)
总是str
。- 如果您想在格式化之前将对象转换为
str
,请使用!s
。 :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/