索引正向從0開始,逆向從-1開始
N:切片開始位置
M:切片結束位置(不包含)
P:指定切片步長,爲正數表示按照指定步長正向切片,爲負數反之
1、列表的切片操做
列表切片後仍是列表
經過列表生成器定義一個列表:ide
In [2]: a = [n for n in range(10)] In [3]: a Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
經過切片淺拷貝對象:code
In [4]: a[:] Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [5]: a[::] Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
指定開始切片位置:對象
In [6]: a[1:] Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9] In [7]: a[1::] Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
指定切片範圍(不包含結束):索引
In [8]: a[1:5] Out[8]: [1, 2, 3, 4] In [9]: a[2:6:] Out[9]: [2, 3, 4, 5]
指定步長切片:字符串
In [10]: a[0:9:3] Out[10]: [0, 3, 6] In [11]: a[0:9:2] Out[11]: [0, 2, 4, 6, 8]
指定步長方向:generator
In [12]: a[9:0:-2] Out[12]: [9, 7, 5, 3, 1] In [13]: a[9:0:-3] Out[13]: [9, 6, 3]
經過切片逆置列表:it
In [15]: a[::-1] Out[15]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
2、元組切片
元組切片後仍是元組,用法和列表切片同樣,可是一點須要注意class
In [17]: b = (n for n in range(5)) In [18]: b Out[18]: <generator object <genexpr> at 0x00000206445ED780> # 推到式經過小括號()之後就不是元組了,是生成器的另外一種形式 In [19]: b = tuple(n for n in range(5)) In [20]: b Out[20]: (0, 1, 2, 3, 4) In [21]: b[::-1] Out[21]: (4, 3, 2, 1, 0) In [22]: b[0:2:] Out[22]: (0, 1)
3、字符串切片
字符串切片以後仍是字符串,用法也和列表切片一致object
In [23]: c = "hello,world" In [24]: c[::-1] Out[24]: 'dlrow,olleh' In [25]: c[0:5:] Out[25]: 'hello'