
3.3 字符串类型
仅有数字类型在日常生活中显然是不够的,为了更方便地对文本数据和对象进行处理,Python中引入了我们在其他语言也熟悉的数据类型——String。
3.3.1 字符串的定义

在创建字符串时,需要用引号来进行声明。Python提供了单引号、双引号、三引号三种方式来定义字符串。实例如下。
【例3-20】单引号定义字符串。

另外,Python还允许引号间的嵌套,例如,单引号可被嵌套进双引号。同时这种多引号的表达方式还可以解决某些书写的兼容问题。
【例3-21】双引号定义字符串。

在此实例中英语书写语句中的'被双括号兼容但是却被单引号错误识别。因此在实际使用中,即使引号间没有区别,还是需要根据实际使用情况进行选择。
另外,三引号的使用方法也较为特殊,三引号允许换行,输出自动多行拼接。但是单引号和双引号就不允许换行,实例如下。
【例3-22】三引号定义字符串。

在字符串的定义过程中,也可能遇到如下情况:

可以看到,字符串被从中间换行了。这就是接下来要介绍的“转义字符”。
在上述实例中,\n为转义字符,代表换行。Python的常见转义字符及其含义如表3-9所示。
表3-9 转义字符

转义字符在书写格式上提供了很大的便利性,但是如果并不想让转义字符对应的字符起作用,而是单纯的正常显示,可以在字符串前加上r或者将转义字符的\用\\替换。实例如下。
【例3-23】屏蔽字符。

3.3.2 字符串格式化

不同于数字类型的操作,字符串的操作更加多样化,和其他语言一样,字符串的基本操作——格式化输出,依旧是重点。格式化输出是计算机语言必不可少的部分。
格式符存在的目的是为真实值进行占位,方便控制显示输出的格式。格式符主要有以下类别,如表3-10所示。
表3-10 格式化操作符

对Python的输出可以进一步进行控制,采用如下方式。

其格式含义如下。

其中的格式参数内容如下。
- name:命名可以选择,用于指定key。
- flags:对齐方式,表示右对齐,-表示左对齐,0表示用0填充,若为空格则表示正数左侧填充空格。
- width:显示宽度。
- precision:小数点后精度。
- typecode:格式化操作符。
具体实例如下。
【例3-24】格式化输出数值。

Python中内置的%操作符可用于格式化字符串操作,控制字符串的输出。Python中还有其他的格式化字符串的方式,但%操作符是最基础最方便的。
其他的还有在后面将会讲到的format()方法。
3.3.3 字符串内置的函数

Python为字符串操作提供了全面而多样的内置函数,涉及字符串的替换、删除、复制、拼接、比较和查找等各个方面。下面来了解部分常用的函数。
(1)字符串的搜索和替换。
包括以下内置的函数,如表3-11所示。
表3-11 字符串的搜索和替换的内置函数

使用范例如下。
【例3-25】字符串替换函数。

需要注意的是,字符串的位置查找返回的下标中,字符串第一个字符的下标被定义为0。
(2)字符串去空格。
字符串去空格的函数如表3-12所示。
表3-12 字符串去空格的函数

因为方法简单,故不再列举实例。
(3)字符串判断。
字符串判断的函数如表3-13所示。
表3-13 字符串判断的函数

(4)字符串的分割截取。
【例3-26】字符串分割截取。

(5)字符串的拼接。
Pyhton提供了str.join()方法来进行字符串的拼接操作。实例如下。
【例3-27】字符串拼接。
