yangwu-183

Python 中一对单引号和一对双引号都可表示一个字符串: 

1 Str1 = \'python\' 
2 Str2 = "python"

思考? 如何表示字符串: I \' am a python coder. 

方法一, 用单引号加转义字符  \' \ \':

1 Str1 = \'I \\' am a python coder.\'

 转义字符 \ 改变原来单引号的含义,在此处表示特殊含义。

思考?如何表示字符串: \'A\' and  \'a\' are two different letters.

方法一, 继续用转义字符 \' \ \' :

1 Str = \' \\'A\\' and \\'a\\' are two different letters.\'

此时代码不仅不易读且容易出错,故可使用双引号 " " + \' \' 单引号的方式:

1 Str = " \'A\' and \'a\' are two different letters. "

反之如果字符串中有双引号括起来的单词,外面就使用单引号 \' \' :

1 Str1 = \' "A" and "a" are different letters. \' 
2 Str2 = \'hello, "{}"\'.format(\'python\')

 

总结: python 会将外层的单引号或双引号看做字符串的标识,内层的单引号或双引号看做是普通的字符,

   只不过内层引号和外层引号不能同时使用一个类型,外层用单引号内层就用双引号,外层用双引号内层就用单引号。

1 Str1 = \' hello "python" \'
2 Str2 = " hello \'python\' "

 

三个单引号 \'\'\' \'\'\' 和三个双引号 """ """ :

当一行代码过多时,我们希望换行显示并且保留原来的格式,此时用三个单引号\'\'\' \'\'\' 和 三个双引号 """ """ 表示 :

1 Str = """ my name is
2           yangwu
3           I like coding"""

 

分类:

技术点:

相关文章: