品易云推流 关闭
文章详情页
文章 > Python常见问题 > python如何输入单引号

python如何输入单引号

头像

silencement

2019-09-21 09:42:283692浏览 · 0收藏 · 0评论

实际上在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.

一般而言不经常使用三引号'''...'''及"""..."""
但三引号有一个特殊的性质:会自动在每一行末尾加上换行标志,这样输入和输出的字符串就会是同样的样式:

>>> 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
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图