
2.4.2 字符串的基本操作与方法
1.获取多个字符
使用[ ]除了可以获取单个字符外,还可以指定一个范围来获取多个字符,也就是一个子串或者片段,具体格式为:

式中,strname是要截取的字符串;start表示要截取的第一个字符所在的索引(截取时包含该字符),如果不指定,默认为0,也就是从字符串的开头截取;end表示要截取的最后一个字符所在的索引(截取时不包含该字符),如果不指定,默认为字符串的长度;step指的是从start索引处的字符开始,每step个距离获取一个字符,直至end索引处的字符,step默认值为1,当省略该值时,最后一个冒号也可以省略。
【例2-35】 字符串的访问。

运算结果:

2.获取字符串长度或字节数
字符串的长度一般用len函数,其基本语法格式为:

式中,string用于指定要进行长度统计的字符串。
字符串长度不等于字节数,后者需要使用encode()方法将字符串进行编码后再获取它的字节数。
【例2-36】 字符串的长度与字节数。

运算结果:

从例中可以看到,1个汉字,其字符长度就是1,但中英文不同的字符所占的字节数不同,导致其占用字节数不同。一个汉字可能占2~4个字节,具体占多少个,取决于采用的编码方式。例如,汉字在GBK/GB2312编码中占用2个字节,而在UTF-8编码中一般占用3个字节。

2-5 分割字符串
3.分割字符串
split()方法可以实现将一个字符串按照指定的分隔符切分成多个子串,这些子串会被保存到列表中(不包含分隔符),作为方法的返回值反馈回来。该方法的基本语法格式如下:

式中,str表示要进行分割的字符串;sep用于指定分隔符,可以包含多个字符,此参数默认为None,表示所有空字符,包括空格、换行符“\n”、制表符“\t”等;maxsplit是可选参数,用于指定分割的次数,最后列表中子串的个数最多为maxsplit+1,如果不指定或者指定为-1,则表示分割次数没有限制。
在split方法中,如果不指定sep参数,那么也不能指定maxsplit参数。
【例2-37】 字符串的分割。

运算结果:

4.合并字符串
使用join()方法合并字符串时,它会将列表(或元组)中多个字符串采用固定的分隔符连接在一起。
join()方法的语法格式如下:

式中,newstr表示合并后生成的新字符串;str用于指定合并时的分隔符;iterable表示做合并操作的源字符串数据,允许以列表、元组等形式提供。
【例2-38】 字符串的合并。

运算结果:

5.统计字符或字符串出现的次数
count()方法用于检索指定字符或字符串在另一字符串中出现的次数,如果检索的字符串不存在,则返回0,否则返回出现的次数。
count方法的语法格式如下:

式中,str表示原字符串;sub表示要检索的字符串;start指定检索的起始位置,也就是从什么位置开始检测,如果不指定,默认从头开始检索;end指定检索的终止位置,如果不指定,则表示一直检索到结尾。
【例2-39】 统计字符出现的频率。

运算结果:


6.检测字符串中是否包含某子串
find()方法用于检索字符串中是否包含目标字符串,如果包含,则返回第一次出现该字符串的索引;反之,则返回-1。
find()方法的语法格式如下:

式中,str表示原字符串;sub表示要检索的目标字符串;start表示开始检索的起始位置。如果不指定,则默认从头开始检索;end表示结束检索的结束位置。如果不指定,则默认一直检索到结尾。
Python还提供了rfind()方法,与find()方法最大的不同在于,rfind()是从字符串右边开始检索。
【例2-40】 检索字符串中是否包含目标字符串。

运算结果:

同find()方法类似,index()方法也可以用于检索是否包含指定的字符串,不同之处在于,当指定的字符串不存在时,index()方法会抛出异常。
index()方法的语法格式如下:

式中,str表示原字符串;sub表示要检索的子字符串;start表示检索开始的起始位置,如果不指定,默认从头开始检索;end表示检索的结束位置,如果不指定,默认一直检索到结尾。
和index()方法类似,rindex()方法的作用是从右边开始检索。
【例2-41】 用index()检索字符串中是否包含目标字符串。

运算结果:


startswith()方法用于检索字符串是否以指定字符串开头,如果是,返回True;反之返回False。此方法的语法格式如下:

式中,str表示原字符串;sub表示要检索的子串;start表示指定检索开始的起始位置索引,如果不指定,则默认从头开始检索;end表示指定检索的结束位置索引,如果不指定,则默认一直检索到结束。
endswith()方法则用于检索字符串是否以指定字符串结尾,如果是则返回True;反之则返回False。该方法的语法格式如下:

7.字符串对齐

2-6 字符串对齐
Python提供了3种可用来进行文本对齐的方法,分别是ljust()、rjust()和center()方法。
ljust()方法的功能是向指定字符串的右侧填充指定字符,从而达到左对齐文本的目的,基本格式如下:

式中,S表示要进行填充的字符串;width表示包括S本身长度在内,字符串要占的总长度;fillchar作为可选参数,用来指定填充字符串时所用的字符,默认情况使用空格。
rjust()和ljust()方法类似,唯一的不同在于,rjust()方法是向字符串的左侧填充指定字符,从而达到右对齐文本的目的,其基本格式如下:

center()字符串方法与ljust()和rjust()的用法类似,但它让文本居中,而不是左对齐或右对齐,其基本格式如下:

【例2-42】 字符串的对齐。

运算结果:


8.字符串的其他方法
为了方便对字符串中的字母进行大小写转换,字符串变量提供了3种方法,分别是title()、lower()和upper()。
title()方法用于将字符串中每个单词的首字母转为大写,其他字母全部转为小写,转换完成后,此方法会返回转换得到的字符串。如果字符串中没有需要转换的字符,此方法会将字符串原封不动地返回。title()方法的语法格式如下:

lower()方法用于将字符串中的所有大写字母转换为小写字母,转换完成后,该方法会返回新得到的字符串。如果字符串中原本就都是小写字母,则该方法会返回原字符串。
upper()的功能和lower()方法恰好相反,它用于将字符串中的所有小写字母转换为大写字母,和以上两种方法的返回方式相同,即如果转换成功,则返回新字符串;反之,则返回原字符串。
Python还提供了3种方法来删除字符串中多余的空格和特殊字符,它们分别是:
● strip()方法用于删除字符串前后(左右两侧)的空格或特殊字符;
● lstrip()方法用于删除字符串前面(左边)的空格或特殊字符;
● rstrip()方法用于删除字符串后面(右边)的空格或特殊字符。