使用 __repr__() 了解双引号和单引号之间的区别

Understanding difference between Double Quote and Single Quote with __repr__()

printobjectrepr()有什么区别? 为什么打印格式不同?

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'

__str____repr__ 都是获取对象的字符串表示的方法。 __str__ 应该更短且更易于使用,而 __repr__ 应该提供更多细节。

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

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

关于 printstrreprprint 打印 没有附加引号的给定字符串,而str 将从给定对象(在本例中为字符串本身)创建 一个字符串,repr 创建 一个"representation string" 来自对象(即包含一组引号的字符串)。简而言之shell,strrepr的区别应该是str对用户来说容易理解repr很容易理解for Python.

此外,如果您在交互式 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'"

参见__repr__

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

__str__

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead.

强调是我加的。