Python基础学习之序列(1)
序列
序列类型有着相同的访问模式:它的每一个元素可以通过指定一个偏移量的方式得到。而多个元素可以通过切片操作的方式一次得到,下标偏移量是从0开始到总元素-1结束,之所以要减1是因为我们是从0开始计数的;
序列类型操作符
序列操作符 作用
seq[index] 获得下标为index元素
seq[ind1:ind2] 获得下标从ind1到ind2间的元素集合
seq*expr 序列重复expr次
seq1+seq2 连接序列seq1和seq2
obj in seq 判断obj元素是否包含在sep中
obj not in seq 判断obj元素是否不包含在seq中
连接操作符(+)
这个操作符允许我们把一个序列和另一个相同类型的序列做连接。
示例:
>>> seq1='My name is '
>>> seq2='JustZhi'
>>> seq1+seq2
'My name is JustZhi'
>>> seq='Hello everyone!'>>> seq+seq1+seq2
'Hello everyone!My name is JustZhi'
>>> seq2+seq1+seq
'JustZhiMy name is Hello everyone!'
>>> seq+seq2
'Hello everyone!JustZhi'
>>> seq3=['Lilei','Hanmeimei','Xiaoming']
>>> seq+seq3
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
seq+seq3
TypeError: Can't convert 'list' object to str implicitly
>>> seq4=['Zhang3','Li4']
>>> seq3+seq4
['Lilei', 'Hanmeimei', 'Xiaoming', 'Zhang3', 'Li4']
>>> seq4+seq3
['Zhang3', 'Li4', 'Lilei', 'Hanmeimei', 'Xiaoming']
>>>
重复操作符(*)
示例:
>>> seq1='My name is '
>>> seq2='JustZhi'
>>> seq='Hello everyone!'
>>> seq4=['Zhang3','Li4']
>>> seq3=['Lilei','Hanmeimei','Xiaoming']
>>> seq4*4
['Zhang3', 'Li4', 'Zhang3', 'Li4', 'Zhang3', 'Li4', 'Zhang3', 'Li4']
>>> seq*2
'Hello everyone!Hello everyone!'
>>> seq+seq4*3
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
seq+seq4*3
TypeError: Can't convert 'list' object to str implicitly
>>> seq+seq2*3
'Hello everyone!JustZhiJustZhiJustZhi'
>>> (seq+seq2)*3
'Hello everyone!JustZhiHello everyone!JustZhiHello everyone!JustZhi'