python里单引号怎么打
2024-08-01
来源:化拓教育网
实际上在Python中'...'和"..."是完全一样的,但不能出现'..."和"...'这种情况。
而将其混合使用会有很多意想不到的效果:
具体规则如下:
若字符串没有引号嵌套,则对可打印转义字符(\\,\',\",\ooo,\xhh)进行转义。
若字符串有引号嵌套,则对嵌套内部字符全部不进行转义,保持原始格式;对嵌套外部字符参照1进行转义。
注意print会对所有转义字符进行转义。
下面是几个有代表性的例子:
>>> '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.
更多学习内容,请点击。