是什么区别print
,object
和repr()
?为什么要以不同的格式打印?
参见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和很多程序员似乎更喜欢'
,虽然)。
>>> 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'
About print
,str
and repr
:print
将打印给定的字符串而没有其他引号,而str
将从给定的对象创建一个字符串(在这种情况下为字符串本身),并从该对象repr
创建一个“表示字符串”(即,包含一组字符串的字符串)引号)。简而言之,之间的区别str
,并repr
应该是str
很容易理解的用户,并repr
很容易理解为Python。
另外,如果您在交互式外壳程序中输入任何表达式,Python会自动回repr
显结果。这可能会造成一些混乱:在交互式外壳中,执行此操作print(x)
时所看到的是str(x)
;使用时str(x)
,看到的是repr(str(x))
,使用时repr(x)
,看到的repr(repr(x))
(因此双引号)。
>>> 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'"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句