python如何输入单引号
实际上在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. Second line.' >>> s # 对不可打印字符不进行转义 'First line. Second line.' >>> print s # print对所有转义字符进行转义 First line. Second line.
一般而言不经常使用三引号'''…'''及"""…"""
但三引号有一个特殊的性质:会自动在每一行末尾加上换行标志,这样输入和输出的字符串就会是同样的样式:
>>> a=''' #这里的是转行标志 p y t h o n ''' >>> a #字符串的实际内容 ' p y t h o n ' >>> print a #print结果同输入一样 p y t h o n
来源:PY学习网:原文地址:https://www.py.cn/article.html