
上QQ阅读APP看书,第一时间看更新
2.5 三引号字符串
可以使用一对单引号('
)或一对双引号("
)来表示字符串,也可以用一对三引号(三个双引号" " "
或三个单引号' ' '
)来表示字符串。Style Guide for Python Code推荐使用三个双引号(" " "
)。使用三引号可以创建以下三类字符串:
- 多行字符串;
- 包含单引号或双引号的字符串;
- 文档字符串,是用来详细记录某些程序组件用途的一种推荐方法。
字符串中包含引号
在由单引号界定的字符串中可以包含双引号:

但不能包含单引号:

如果需要包含单引号,需要使用转义字符“\'
”

由于单引号字符串中含有单引号,代码段[2]
显示语法错误。IPython显示引起语法错误的代码行的信息,并使用“^
”符号指向发生错误的位置。还会显示更详细的信息“SyntaxError:invalid syntax
”。
由双引号分隔的字符串中可以含有单引号:

但不能包含双引号,如需包含双引号,要使用转义字符“\"
”:

为了避免在字符串中使用“\'
”和“\"
”,可以将这些字符串括在三引号中,例如:

多行字符串
下面的代码段将三引号括起来的多行字符串赋值给变量triple_quoted_string
:

因为在按下Enter键之前没有输入结束符(" " "
),因此IPython知道字符串是不完整的,会显示一个延续提示符“...:
”。可在其后面输入多行字符串的下一行,直到输入结束符(" " "
)并按Enter键。下面的代码段显示triple_quoted_string
的值:

Python通过嵌入换行符来存储多行字符串。例如,当评估triple_quoted_string
而不是打印它时,IPython会将它显示在单引号中,并在代码段[7]
中按Enter键的位置显示一个转义字符“\n
”。IPython显示的引号不是字符串的一部分,而是表示triple_quoted_string
的类型为字符串,显示如下:
