F弦表示与Str()不同

发布于 2025-02-03 18:12:16 字数 374 浏览 2 评论 0 原文

我一直以为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调用什么功能?

I had always thought that f-strings invoked the __str__ method. That is, f'{x}' was always the same as str(x). However, with this class

class Thing(enum.IntEnum):
    A = 0

f'{Thing.A}' is '0' while str(Thing.A) is 'Thing.A'. This example doesn't work if I use enum.Enum as the base class.

What functionality do f-strings invoke?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请帮我爱他 2025-02-10 18:12:17

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 call format(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 think str() is the method used in f-strings.

The docs cover the options you have with __format__ in detail: Link to Documentation

千紇 2025-02-10 18:12:16

来自 格式() 协议”,这意味着 __格式__格式一个>魔术方法而不是 __ str __

class Foo:
    def __repr__(self):
        return "Foo()"

    def __str__(self):
        return "A wild Foo"
    
    def __format__(self, format_spec):
        if not format_spec:
            return "A formatted Foo"
        return f"A formatted Foo, but also {format_spec}!"

>>> foo = Foo()
>>> repr(foo)
'Foo()'
>>> str(foo)
'A wild Foo'
>>> format(foo)
'A formatted Foo'
>>> f"{foo}"
'A formatted Foo'
>>> format(foo, "Bar")
'A formatted Foo, but also Bar!'
>>> f"{foo:Bar}"
'A formatted Foo, but also Bar!'

如果您不希望调用 __格式__ ,则可以指定!S (对于 str ),!r (对于 repr )或!a (对于 ascii )在表达式之后:

>>> foo = Foo()
>>> f"{foo}"
'A formatted Foo'
>>> f"{foo!s}"
'A wild Foo'
>>> f"{foo!r}"
'Foo()'

这有时对字符串很有用:

>>> key = 'something\n nasty!'
>>> error_message = f"Key not found: {key!r}"
>>> error_message
"Key not found: 'something\\n nasty!'"

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__.

class Foo:
    def __repr__(self):
        return "Foo()"

    def __str__(self):
        return "A wild Foo"
    
    def __format__(self, format_spec):
        if not format_spec:
            return "A formatted Foo"
        return f"A formatted Foo, but also {format_spec}!"

>>> foo = Foo()
>>> repr(foo)
'Foo()'
>>> str(foo)
'A wild Foo'
>>> format(foo)
'A formatted Foo'
>>> f"{foo}"
'A formatted Foo'
>>> format(foo, "Bar")
'A formatted Foo, but also Bar!'
>>> f"{foo:Bar}"
'A formatted Foo, but also Bar!'

If you don't want __format__ to be called, you can specify !s (for str), !r (for repr) or !a (for ascii) after the expression:

>>> foo = Foo()
>>> f"{foo}"
'A formatted Foo'
>>> f"{foo!s}"
'A wild Foo'
>>> f"{foo!r}"
'Foo()'

This is occasionally useful with strings:

>>> key = 'something\n nasty!'
>>> error_message = f"Key not found: {key!r}"
>>> error_message
"Key not found: 'something\\n nasty!'"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文