'
和之间没有语义差异"
。'
如果字符串包含,则可以使用"
,反之亦然,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易于理解。repr
print
str
repr
str
repr
str
repr
此外,如果您在交互式 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'"