
2.1.2 序列的通用操作

2-1 序列的通用操作
1.序列索引
序列中的每个元素被分配一个序号:即元素的位置,也称为索引。第一个索引是0,第二个则是1,以此类推,如图2-1所示。

图2-1 序列索引值示意
索引值可以是负数,此类索引是从右向左计数,换句话说,从最后一个元素开始计数,从索引值-1开始,如图2-2所示。需要注意的是,索引下标不是从0开始。

图2-2 负值索引示意
【例2-1】 字符串的正负索引。

运算结果:

本例中,中文字符跟英文字符一样,都是占据1个索引。
2.序列切片
切片操作是访问序列中元素的另一种方法,它可以访问一定范围内的元素,通过切片操作,可以生成一个新的序列。
序列实现切片操作的语法格式如下:

其中,各个参数的含义如下。
1)sname:表示序列的名称。
2)start:表示切片的开始索引位置(包括该位置),此参数也可以不指定,会默认为0,也就是从序列的开头进行切片。
3)end:表示切片的结束索引位置(不包括该位置),如果不指定,则默认为序列的长度。
4)step:表示在切片过程中,隔几个存储位置(包含当前位置)取一次元素,也就是说,如果step的值大于1,则在进行切片取序列元素时,会“跳跃式”地取元素。如果省略设置step的值,则最后一个冒号就可以省略。
【例2-2】 字符串的序列切片及显示。

运算结果:

3.序列相加
在Python中,支持两种类型相同的序列使用“+”运算符做相加操作,它会将两个序列进行连接,但不会去除重复的元素。这里所说的“类型相同”,指的是“+”运算符的两侧序列要么都是序列类型,要么都是元组类型,要么都是字符串。
【例2-3】 字符串的序列相加。

运算结果:

4.序列相乘
在Python中,使用数字n乘以一个序列会生成新的序列,其内容为原来序列重复n次的结果。
【例2-4】 字符串的序列相乘。

运算结果:

5.检查元素是否包含或不包含在序列中
在Python中,可以使用in关键字检查某元素是否为序列的成员,其语法格式为:

其中,value表示要检查的元素,sequence表示指定的序列。
和in关键字用法相同,但功能恰好相反的,还有not in关键字,用于检查某个元素是否不包含在指定的序列中
【例2-5】 检查元素是否包含或不包含在序列中。

运算结果:
