
6-9 再谈字符串
3-4节介绍了字符串的概念,在Python的应用中可以将单一字符串当作一个序列,这个序列是由字符(character)所组成的,可想成字符序列。不过字符串与列表不同的是,字符串内的单一元素内容是不可更改的。
6-9-1 字符串的索引
可以使用索引值的方式取得字符串内容,索引方式则与列表相同。
程序实例ch6_39.py:使用正值与负值的索引列出字符串元素内容。

执行结果

6-9-2 字符串切片
6-1-3节介绍的列表切片可以应用在字符串,下面将直接以实例说明。
程序实例ch6_40.py:字符串切片的应用。

执行结果

6-9-3 函数或方法
除了会变动内容的列表函数或方法不可应用于字符串外,其他则可以用于字符串。

程序实例ch6_41.py:将函数len()、max()、min()应用于字符串。

执行结果

6-9-4 将字符串转成列表
list()函数可以将参数内的对象转成列表,下列是字符串转为列表的实例。

6-9-5 切片赋值应用
字符串本身无法用切片方式更改内容,但是将字符串改为列表后,就可以使用切片更改列表内容了,下面是延续6-9-4节的实例。

6-9-6 使用split()处理字符串
这个方法可以将字符串以空格为分隔符,将字符串拆开,变成一个列表。变成列表后可以使用len()获得此列表的元素个数,这相当于可以计算字符串是由多少个英文字母组成的。由于中文字之间没有空格,所以本节所述方法只适用于纯英文文件。如果我们可以将一篇文章或一本书读至一个字符串变量后,使用这个方法获得这一篇文章或这一本书的字数。
程序实例ch6_41_1.py:获得字符串内的字数。

执行结果

6-9-7 字符串的其他方法
本节将讲解下列字符串方法。startswith()和endswith()如果是真则返回True,如果是假则返回False。
(1)startswith():可以列出字符串起始文字是否是特定子字符串。
(2)endswith():可以列出字符串结束文字是否是特定子字符串。
(3)count():可以列出字符串内特定子字符串出现次数。
程序实例ch6_41_2.py:列出字符串“CIA”是不是起始或结束字符串,以及出现次数。

执行结果

当有一本小说时,可以由此方法计算各个人物出现次数,也可由此判断哪些人是主角哪些人是配角。