Python 中的 !r 和 %r 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33097143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between !r and %r in Python?
提问by b_pcakes
As the title states, what is the difference between these two flags? It seems they both convert the value to a string using repr()? Also, in this line of code:
正如标题所述,这两个标志有什么区别?似乎他们都使用 repr() 将值转换为字符串?此外,在这行代码中:
"{0!r:20}".format("Hello")
What does the 0 in front of the !r do?
!r 前面的 0 有什么作用?
采纳答案by Martijn Pieters
%r
is not a valid placeholder in the str.format()
formatting operations; it only works in old-style %
string formatting. It indeed converts the object to a representation through the repr()
function.
%r
不是str.format()
格式化操作中的有效占位符;它仅适用于旧式%
字符串格式。它确实通过repr()
函数将对象转换为表示。
In str.format()
, !r
is the equivalent, but this also means that you can now use all the format codesfor a string. Normally str.format()
will call the object.__format__()
method on the object itself, but by using !r
, repr(object).__format__()
is used instead.
In str.format()
,!r
是等价的,但这也意味着您现在可以使用字符串的所有格式代码。通常str.format()
会object.__format__()
在对象本身上调用该方法,但通过使用!r
,repr(object).__format__()
改为使用。
There are also the !s
and (in Python 3) !a
converters; these apply the str()
and ascii()
functions first.
还有!s
和(在 Python 3 中)!a
转换器;这些首先应用str()
和ascii()
功能。
The 0
in front indicates what argument to the str.format()
method will be used to fill that slot; positional argument 0
is "Hello"
in your case. You could use namedarguments too, and pass in objects as keyword arguments:
在0
前面指示什么参数的str.format()
方法将被用于填充该插槽; 位置参数0
是"Hello"
在您的案件。您也可以使用命名参数,并将对象作为关键字参数传入:
"{greeting!r:20}".format(greeting="Hello")
Unless you are using Python 2.6, you can omit this as slots without indices or names are automatically numbered; the first {}
is 0
, the second {}
takes the second argument at index 1
, etc.
除非您使用的是 Python 2.6,否则您可以省略它,因为没有索引或名称的插槽会自动编号;第一个{}
是0
,第二{}
个在 index 处采用第二个参数,依此类推1
。