
2.2 String类型
1. 定义
String类型就是字符串,用来存储一段文字。Python中将一段文字放在单引号、双引号或者三引号中即表示一个字符串,如图2-1所示。

图2-1
2. 特殊字符的处理
有时在字符串中会出现单引号或者双引号,此时我们需要对其进行处理,处理方式有以下两种。
方法一:对字符串中出现的特殊字符进行转义,就是告诉Python解释器当前的字符均为普通字符,不做特殊处理,Python中的转义符为反斜线(\),如图2-2所示。

图2-2
输出结果:
>>> Let's learn Python
方法二:通过引号的嵌套解决字符串中的引号问题,如图2-3所示。
输出结果:
>>> Let's learn Python
3. 访问字符串中的字符
在Python中字符串存储在一个以0开始、使用整数索引的字符串序列中,所以要取得某一个字符可以使用索引值,如图2-4所示。

图2-4
分别输出:
>>> L >>> ' >>> []
4. 字符串运算
拼接字符串,如图2-5所示。

图2-5
输出:
>>> Helloword
重复输出字符串,如图2-6所示。

图2-6
输出:
>>> HelloHelloHello
5. 格式化字符串
格式化输出字符串。通常用来将一个值插入到字符串中,如图2-7所示。

图2-7
输出:
>>> Hello word!
Python不仅可以将一个字符串插入到另一个字符串中,还可以通过格式化符号进行更复杂的操作,如表2-1所示。
表2-1

Python中str对象专门提供了一个字符串格式化方法,如图2-8所示。

图2-8
输出:
>>> Hello word!
6. 字符串切片
要提取字符串中的部分值,可以使用切片运算符s[i:j]。这样会提取字符串s中从索引i开始一直到索引j的所有字符k,k的范围是i≤k<j;如果省略i,则从0开始;如果省略j,则一直提取到字符串结尾。三种情况如图2-9所示。

图2-9
输出:
>>> Let >>> learn Python >>> 's
7. Unicode字符串
Python中定义Unicode字符串时需要在引号前加小写字母“u”,如图2-10所示。

图2-10
输出:
>>> 我爱Python
8. Python字符串内建函数
由于字符串是一个非常重要的对象,Python针对字符串增加了很多内建函数。String对象的定义可以在Lib/string.py中找到。