gpt4 book ai didi

python - !r 在 Python 中是什么意思?

转载 作者:行者123 更新时间:2023-12-04 03:47:47 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What does !r do in str() and repr()?

(1 个回答)


1年前关闭。




我在一个项目中找到了以下代码。
!r有什么用部分是什么意思?

def __repr__(self):
return f"user={self.user!r}, variant={self.variant!r}"

最佳答案

默认情况下,一个 f 字符串显示调用 str 的结果在花括号内的值上。指定 !r显示调用结果 repr反而。
来自 docs

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.

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

关于python - !r 在 Python 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59234487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com