
实际上在Python中'...'和"..."是完全一样的,但不能出现'..."和"...'这种情况。
而将其混合使用会有很多意想不到的效果:
具体规则如下:
若字符串没有引号嵌套,则对可打印转义字符(\\,\',\",\ooo,\xhh)进行转义。
若字符串有引号嵌套,则对嵌套内部字符全部不进行转义,保持原始格式;对嵌套外部字符参照1进行转义。
注意print会对所有转义字符进行转义。
下面是几个有代表性的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | >>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t' # 对可打印字符转义
"doesn't"
>>> "doesn\'t" # 同上
"doesn't"
>>> "doesn't" # 这样可以省去\
"doesn't"
>>> '"doesn\'t"' # 嵌套后内部全部不进行转义
'"doesn\'t"'
>>> "\"Yes,\" he said." # 同类型引号,需要进行转义
'"Yes," he said.'
>>> '"Yes," he said.' # 这样可以省去\
'"Yes," he said.'
>>> '"Isn\'t," she said.' # 嵌套后内部全部不进行转义
'"Isn\'t," she said.'
>>> print '"Isn\'t," she said.' # print对所有转义字符进行转义
"Isn't," she said.
>>> s='First line.\nSecond line.'
>>> s # 对不可打印字符不进行转义
'First line.\nSecond line.'
>>> print s # print对所有转义字符进行转义
First line.
Second line.
|
一般而言不经常使用三引号'''...'''及"""..."""
但三引号有一个特殊的性质:会自动在每一行末尾加上换行标志,这样输入和输出的字符串就会是同样的样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> a='''\ #这里的\是转行标志
p
y
t
h
o
n
'''
>>> a #字符串的实际内容
'\tp\n\ty\n\tt\n\th\n\to\n\tn\n'
>>> print a #print结果同输入一样
p
y
t
h
o
n
|