• 技术文章 >常见问题 >Python常见问题

    python里单引号怎么打

    silencementsilencement2019-10-11 11:07:49原创16575

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

    更多学习内容,请点击python学习网

    专题推荐:单引号
    上一篇:python怎么传入不确定参数 下一篇:python程序出错怎么处理

    相关文章推荐

    • 在Python中如何获取元素在数组中的索引号?• 详解python中单引号,双引号,多引号区别• python 反引号怎么打• python如何输入单引号

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网