5

Python中,单引号,双引号,三引号的使用区别与原因

 3 years ago
source link: http://www.cnblogs.com/zpynb/p/14349441.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

先说1双引号与3个双引号的区别,双引号所表示的字符串通常要写成一行

如:

s1 = "hello,world"

如果要写成多行,那么就要使用/ (“连行符”)吧,如

s2 = "hello,/

world"

s2与s1是一样的。如果你用3个双引号的话,就可以直接写了,如下:

s3 = """hello,

world,

hahaha.""",那么s3实际上就是"hello,/nworld,/nhahaha.", 注意“/n”,所以,

如果你的字符串里/n很多,你又不想在字符串中用/n的话,那么就可以使用3个双

引号。而且使用3个双引号还可以在字符串中增加注释,如下:

s3 = """hello,  #hoho, this is hello, 在3个双引号的字符串内可以有注释哦

world,          #hoho, this is world

hahaha."""

这里我试过一下,确实可以加注释,不过在print s3的时候连注释内容会一起给打印出来

这就是3个双引号和1个双引号表示字符串的区别了

3个双引号与1个单引号的区别也 是和这个一样的,实际上python支持单引号是有原因的,下面我来比较1个单引号和 1个双引号的区别。

当我用单引号来表示一个字符串时,如果要表示 Let's go 这个字符串,必须这样:
s4 = 'Let/'s go',注意没有,字符串中有一个',而字符串又是用'来表示,所以
这个时候就要使用转义符 / (/,转义符应该知道吧), 如果你的字符串中有一大堆
的转义符,看起来肯定不舒服,python也很好的解决了这个问题,如下:
s5 = "Let's go"
这时,我们看,python知道你是用 " 来表示字符串,所以python就把字符串中的那
个单引号 ' , 当成普通的字符处理了,是不是很简单。
对于双引号,也是一样的,下面举个例子
s6 = 'I realy like "python"!'
这就是单引号和双引号都可以表示字符串的原因了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK