使用__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'

问题答案:

'和之间没有语义差异"'如果字符串包含",反之亦然,则可以使用,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 printstrand reprprint打印 给定的字符串而没有其他引号,而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'"