F弦表示与Str()不同
我一直以为F-string调用 __ str __
方法。也就是说, f'{x}'
始终与 str(x)
相同。但是,使用此类
class Thing(enum.IntEnum):
A = 0
f'{thing.a}'
是'0'
而 str(thing.a)
是' thing.a'
。如果我使用 Enum.Enum
作为基类,则此示例无效。
F-string调用什么功能?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python中的F-SNING不使用
__ str __
或__ epr __
。他们使用__格式__
。因此,要获得与
f'{thing.a}'
相同的结果,您需要调用format(thing.a)
。__格式__(...)
方法允许您添加更多格式化功能(例如,使用浮子,您可以做{:。2f}
将数字舍入至两个小数)) 。如果
格式()
尚未为类/对象定义,则Python将落回__ str __
。这就是为什么大多数人认为str()
是f-strings中使用的方法的原因。文档涵盖了您使用
__格式__
详细介绍的选项:链接到文档f-strings in Python don't use
__str__
or__repr__
. They use__format__
.So to get the same result as
f'{Thing.A}'
, you'd need to callformat(Thing.A)
.The
__format__(...)
method allows you to add more formatting features (for example with floats you can do{:.2f}
to round the number to two decimals).If
format()
hasn't been defined for a class/object, python will fall back to__str__
. That's why most people thinkstr()
is the method used in f-strings.The docs cover the options you have with
__format__
in detail: Link to Documentation来自
格式()
协议”,这意味着__格式__格式一个>魔术方法而不是
__ str __
。如果您不希望调用
__格式__
,则可以指定!S
(对于str
),!r
(对于repr
)或!a
(对于ascii
)在表达式之后:这有时对字符串很有用:
From "Formatted string literals" in the Python reference:
f-strings invoke the "
format()
protocol", meaning that the__format__
magic method is called instead of__str__
.If you don't want
__format__
to be called, you can specify!s
(forstr
),!r
(forrepr
) or!a
(forascii
) after the expression:This is occasionally useful with strings: