Python字符串单引号('...')和双引号("...")的区别

113人浏览   2024-06-15 07:58:10

相比数值,Python提供了可以通过几种不同方式表示的字符串。它们可以用单引号(’...’)或双引号(”...”)标识。\可以用来转义引号:

在交互式解释器中,输出的字符串会用引号引起来,特殊字符会用反斜杠(\)转义。虽然可能和输入看上去不太一样,但是两个字符串是相等的。如果字符串中只有单引号而没有双引号,就用双引号引用,否则就用单引号引用。示例如下:

>>> 'spam eggs'                    #单纯的单引号字符串spam eggs
'spam eggs'
>>> 'doesn\'t'                       #字符串doesn\'t 只有单引号,所以用双引号引用
"doesn't"
>>> "doesn't"                        #字符串doesn\'t 只有单引号,所以用双引号引用
"doesn't"
>>> '"Yes," he said.'               #字符串“Yes,” he said .有双引号,所以用单引号引用
'"Yes," he said.'
>>> "\"Yes,\" he said."           #字符串\"Yes,\" he said. 有双引号,所以用单引号引用
'"Yes," he said.'
>>> '"Isn\'t," she said.'           #字符串"Isn\'t," she said.有单引号也有双引号,所以用单引号引用
'"Isn\'t," she said.'

print()语句可以生成可读性更好地输出,它会省去引号并且打印出转义后的特殊字符:

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')         #省去单引号,打印出转义\'
"Isn't," she said.
>>> s = 'First line.\nSecond line.'
>>> s
'First line.\nSecond line.'                #不用print,没有省去单引号,也没做转义\n
>>> print(s)                                   #用print输出,省去单引号,打印转义\n
First line.
Second line.

与其他语言不同,特殊字符例如\n在单引号('...')和双引号("...")中具有相同的含义,两者唯一的区别是在单引号中,你不需要转义 " (但你必须转义 ' ),反之亦然。

如果你前面带有\ 的字符被当作特殊字符,你可以使用原始字符串,方法是在第一个引号前面加上一个r:

>>> print('C:\some\name')
C:\some
ame                                              #第一个引号前没有加r,\name直接当做转义\n和ame输出
>>> print(r'C:\some\name')
C:\some\name															#加了原始字符串r,原封不动的输出引号后的字符串