问题描述
print
,object
和repr()
有什么区别?为什么要以不同的格式打印?
What is the difference between print
, object
, and repr()
?Why is it printing in different formats?
请参见output difference
:
>>> x="This is New era"
>>> print x # print in double quote when with print()
This is New era
>>> x # x display in single quote
'This is New era'
>>> x.__repr__() # repr() already contain string
"'This is New era'"
>>> x.__str__() # str() print only in single quote ''
'This is New era'
推荐答案
'
和"
之间没有语义差异.如果字符串包含"
(反之亦然),则可以使用'
,Python也会这样做.如果字符串中包含这两个字符串,则必须转义其中的某些字符串(或使用三引号"""
或'''
). (如果同时使用'
和"
,则Python和许多程序员似乎更喜欢'
.)
There is no semantic difference between '
and "
. You can use '
if the string contains "
and vice versa, and Python will do the same. If the string contains both, you have to escape some of them (or use triple quotes, """
or '''
). (If both '
and "
are possible, Python and many programmers seem to prefer '
, though.)
>>> x = "string with ' quote"
>>> y = 'string with " quote'
>>> z = "string with ' and \" quote"
>>> x
"string with ' quote"
>>> y
'string with " quote'
>>> z
'string with \' and " quote'
关于print
,str
和repr
:print
将打印给定的字符串,且不带附加引号,而str
将创建给定对象的字符串(在这种情况下为字符串本身)和repr
从对象创建一个表示字符串"(即,包含一组引号的字符串).简而言之,str
和repr
之间的区别应该在于str
对于用户来说容易理解 和repr
对于Python来说易于理解的 >.
About print
, str
and repr
: print
will print the given string with no additional quotes, while str
will create a string from the given object (in this case, the string itself) and repr
creates a "representation string" from the object (i.e. the string including a set of quotes). In a nutshell, the difference between str
and repr
should be that str
is easy to understand for the user and repr
is easy to understand for Python.
此外,如果您在交互式外壳程序中输入任何表达式,Python会自动回显结果的repr
.这可能有点令人困惑:在交互式Shell中,当您执行print(x)
时,您看到的是str(x)
;使用str(x)
时,看到的是repr(str(x))
,使用repr(x)
时,看到的是repr(repr(x))
(因此双引号).
Also, if you enter any expression in the interactive shell, Python will automatically echo the repr
of the result. This can be a bit confusing: In the interactive shell, when you do print(x)
, what you see is str(x)
; when you use str(x)
, what you see is repr(str(x))
, and when you use repr(x)
, you see repr(repr(x))
(thus the double quotes).
>>> print("some string") # print string, no result to echo
some string
>>> str("some string") # create string, echo result
'some string'
>>> repr("some string") # create repr string, echo result
"'some string'"
这篇关于使用__repr __()了解双引号和单引号之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!