
上QQ阅读APP看书,第一时间看更新
6-9 再谈字符串
3-4节笔者介绍了字符串(string)的观念,在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( )处理字符串
这个方法(method),可以将字符串以空格为分隔符,将字符串拆开,变成一个列表。变成列表后我们可以使用len( )获得此列表的元素个数,这相当于可以计算字符串是由多少个英文字母组成,由于中文字之间没有空格,所以本节所述方法只适用在纯英文文件。如果我们可以将一篇文章或一本书当做一个字符串变量,可以使用这个方法获得这一篇文章或这一本书的字数。
程序实例ch6_41_1.py:获得字符串内的字数。

执行结果
