Python 中的 !r 是什么意思?
What does !r mean in Python?
我在一个项目中找到了如下代码
!r
部分是什么意思?
def __repr__(self):
return f"user={self.user!r}, variant={self.variant!r}"
默认情况下,f 字符串显示调用 str on the values inside the curly braces. Specifying !r
displays the result of calling 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().
我在一个项目中找到了如下代码
!r
部分是什么意思?
def __repr__(self):
return f"user={self.user!r}, variant={self.variant!r}"
默认情况下,f 字符串显示调用 str on the values inside the curly braces. Specifying !r
displays the result of calling 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().