Python篇(一) 引号的作用及其区别

这里主要记录一下在 python 中使用单引号, 双引号 和三引号的区别.

当前开发环境

Python 3.5.2

GitHub

HowPy

  • 单引号
# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string1 = 'hello world1'
print(string1)

运行结果

hello world1
  • 双引号
# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string2 = "hello world2"
print(string2)

运行结果

hello world2
  • 三引号
# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string3 = '''hello world3'''
print(string3)

运行结果

hello world3

目前为止,是看不出来它们之间的区别的, 都是 Python 的 String 类型表示方式之一.接下来看下它们的区别:

  • 换行表示(不考虑字符串的拼接)

单引号

# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string11 = 'hello world1' + \
          ' again'
print(string11)

运行结果

hello world1 again

双引号

# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string22 = "hello world2" \
          " again"
print(string22)

运行结果

hello world2 again

三引号

# import !/user/bin/env python
# -*- coding:UTF-8 -*-

string33 = '''hello world3 again '''
print(string33)

运行结果

hello world3 again

从这我们可以看出部分区别出来了, 使用三个引号时, 换行不用添加额外的符号 \ , 而其它两种方式则需要.

  • 使用 三引号 当注释
# import !/user/bin/env python
# -*- coding:UTF-8 -*-

'''
三引号充当注释
'''
string333 = '''hello world3 again '''
print(string333)

运行结果

hello world3 again

可以使用三引号开头及结尾, 类似于上述方式, 充当多行注释用, 而单引号和双引号则不行

  • 混合使用

python的三种引号是可以混搭使用的, 包括 :

单引号嵌套双引号

string111 = '"hello world3 again"'

双引号嵌套单引号

string222 = "'hello world'"

三引号嵌套单双引号

string333 = '''"'hello world3 again '"'''
print(string333)

运行结果

"'hello world3 again '"

值得注意的是, 不要将引号的嵌套与字符串的拼接混淆了, 否则极易出现语法错误

反例

string3333 = ''''hello world3 again ''''

运行结果

SyntaxError: EOL while scanning string literal

Process finished with exit code 1

这结果并非想要的啊, 其原因在与前四个引号是三引号与单引号的混合, 到后三引号的时候, 一个字符串对象完成, 最后的单引号则表示新的字符串的起点, 但却没有结束用的单引号,所以会报语法错误

正例

string3333 = ''''hello world3 again'''"'"
print(string3333)

运行结果

'hello world3 again'

这样就可以得到想要的结果了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值