美文网首页我爱编程
Python篇(一) 引号的作用及其区别

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

作者: me_touch | 来源:发表于2018-04-14 18:18 被阅读0次

这里主要记录一下在 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'

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

相关文章

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

    这里主要记录一下在 python 中使用单引号, 双引号 和三引号的区别. 当前开发环境 GitHub HowPy...

  • 06-字符串基础

    前面我们已经提过,python对单双引号无区别,但单引号或双引号可以相互转义

  • 05-字符串使用基础

    python中,单双引号没有区别,表示一样的含义

  • Python字符串

    字符串创建z = 'python' # 或 z = "python"很多情况下单引号和双引号作用相同,但是一些情况...

  • Python学习笔记之字符串

    字符串是Python中常见的数据类型,在Python中,可以通过单引号或者双引号来创建字符串,它们的作用是一样的,...

  • Python中单引号,双引号,3个引号的区别

    单引号和双引号 在Python中我们都知道单引号和双引号都可以用来表示一个字符串,比如 str1和str2是没有任...

  • Python2--字符串及运算符

    人生苦短,我用 Python 1. 字符串 双引号或单引号标示 字符串拼接 \来去除引号标示字符串的特殊作用 2....

  • 引号的作用

    引号的作用有四种: 一、表示引用的部分。文章中的人物对话或者是直接引用别人的话(或文章)用引号,为的是把他们和作者...

  • Python中的单引号和双引号的区别

    参考回答:https://blog.csdn.net/kevindree/article/details/8679...

  • python 学习笔记

    壹 、 python 基础 摘抄自《a bite of python》 一、字符串 单引号双引号(与单引号完全相同...

网友评论

    本文标题:Python篇(一) 引号的作用及其区别

    本文链接:https://www.haomeiwen.com/subject/flnlkftx.html