
2.5 字符串
2.5.1 字符串的概念
字符串是由零个或多个字符组成的有限串行,是用单引号或者双引号括起来的,符号是str(string的缩写)。下面这些都是字符串。

2.5.2 字符串的连接
字符串的连接是一个比较常见的需求,比如将姓和名进行连接。直接使用操作符+就可以将两个或者两个以上的字符串进行连接。

2.5.3 字符串的复制
有的时候我们需要把一个字符串重复多遍,比如你要把“Python真强大”这句话重复三遍,可以使用操作符*对字符串进行重复。

上面代码对字符串重复三遍,输入*3就可以。你可以根据需要,重复多遍。
2.5.4 获取字符串的长度
手机号、身份证号、姓名都是字符串,想要知道这些字符串的长度,可以利用len()函数来获取字符串长度。


2.5.5 字符串查找
字符串查找是指查找某一个字符串是否包含在另一个字符串中,比如知道一个用户名,你想知道这个用户是不是测试账号(测试账号的判断依据是名字中包含测试两字),那么只要在名字中查找“测试”字符串即可。如果找到了,则说明该用户是测试账号;如果查找不到,则说明不是测试账号。用in或者not in这两种方法均可实现。

除了in和not in,还可以用find,当用find查找某一字符是否存在于某个字符串中时,如果存在则返回该字符的具体位置,如果不存在则返回-1,如下所示。

注意,因为在Python中位置是从0开始数的,所以第3位就是2。

2.5.6 字符串索引
字符串索引是指通过字符串中值所处的位置对值进行选取。需要注意的是字符串中的位置是从0开始的。
获取字符串中第1位的值。

获取字符串中第4位的值。

获取字符串中第2位到第4位之间的值,且不包含第4位的值。

获取字符串中第1位到第4位之间的值,且不包含第4位的值,第1位可以省略不写。

获取字符串中第7位到最后一位之间的值,最后一位可以省略不写。

获取字符串中最后一位的值。

我们把上面这种通过具体某一个位置获取该位置的值的方式称为普通索引;把通过某一位置区间获取该位置区间内的值的方式称为切片索引。
2.5.7 字符串分隔
字符串分隔是先将一个字符用某个分隔符号分开,然后将分隔后的值以列表的形式返回,用到的是split()函数。

2.5.8 移除字符
移除字符用到的方法是 strip()函数,该函数用来移除字符串首尾的指定字符,默认移除字符串首尾的空格或换行符:
