5

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'
4

3 回答 3

6

'和之间没有语义差异"'如果字符串包含,则可以使用",反之亦然,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'

Aboutprint和:将打印str给定的字符串,不带额外的引号,而将从给定的对象(在本例中字符串本身)创建一个字符串,并对象(即包含一组引号)。简而言之, 和 之间的区别应该是用户易于理解和Python易于理解。reprprintstrrepr strreprstrrepr

此外,如果您在交互式 shell 中输入任何表达式,Python 将自动回repr显结果。这可能有点令人困惑:在交互式 shell 中,当你这样做时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'"
于 2016-02-16T09:34:01.707 回答
1

__repr__

由 repr() 内置函数和字符串转换(反引号)调用,以计算对象的“官方”字符串表示。如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象(给定适当的环境)。

并且__str__

由 str() 内置函数和 print 语句调用以计算对象的“非正式”字符串表示。这与 __repr__() 的不同之处在于它不必是有效的 Python 表达式:可以使用更方便或更简洁的表示来代替。

重点是我加的。

于 2016-02-16T09:40:34.047 回答
0

__str__并且__repr__都是获取对象的字符串表示的两种方法。__str__应该更短,更用户友好,同时__repr__应该提供更多细节。

但是,在python中,单引号和双引号没有区别。

于 2016-02-16T09:29:31.503 回答