
上QQ阅读APP看书,第一时间看更新
5.1 字符串基本操作

Python字符串的常用操作,包括字符串的替换、截取、复制、连接、比较、查找等。
在Python中,字符串有时候会有许多的空格,如果想去除空格,就需要以下一些方法。
【例5-1】分别去除字符串两边的空格、字符串左边的空格和字符串右边的空格。
(1)strip():删除字符串两边的指定字符,默认为空格。

(2)lstrip():删除字符串左边的指定字符,默认为空格。

(3)rstrip():删除字符串右边指定字符,默认为空格。

程序运行结果如图5-1所示。
【例5-2】复制字符串。

程序运行结果如图5-2所示。
【例5-3】连接字符串+:连接两个字符串。

程序运行结果如图5-3所示。
【例5-4】使用len()求给定的字符串长度。

程序运行结果如图5-4所示。

图5-1 去除空格结果

图5-2 复制字符串结果

图5-3 连接字符串结果

图5-4 求字符串长度结果
【例5-5】字符串中字母大小写转换。
使用lower()将字符串中的字母转换为小写,upper()将字符串中的字母转换为大写,swapcase()将字符串中的字母大小写互换,capitalize()将字符串中的首字母大写。

程序运行结果如图5-5所示。
【例5-6】使用center()方法将字符串放入中心位置,可指定长度以及位置两边字符。

程序运行结果如图5-6所示。
【例5-7】使用count()进行字符串统计,在给定的字符串中统计特定字符的个数。下面是统计字符串a中字符'l'的个数。

程序运行结果如图5-7所示。
【例5-8】通过[ :]进行字符串切片。

程序运行结果如图5-8所示。

图5-5 字符串字母大小写转换结果

图5-6 字符串放入中心位置结果

图5-7 统计字符串结果

图5-8 切片操作结果