切片

对列表的切片

>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
>>> L[0:3]  # 从索引0开始取, 知道索引3为止, 但不包括索引3. 即0,1,2
['Michael', 'Sarah', 'Tracy']
>>> L[1:3]
['Sarah', 'Tracy']
>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']

切片十分有用, 可以使用切片拿出某一段数据

>>> l = list(range(100))
>>> l[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> l[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l[:10:2]
[0, 2, 4, 6, 8]
>>> l[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
# 什么都不写可以原样复制一个list:
>>> l[:]
[0, 1, 2, 3, 4, 5, 6, ..... 97, 98, 99]
# 元组也是一种list, 唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)

字符串的切片

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'
# 倒切
>>> 'ABCDEFG'[-4:-1]
'DEF'
>>> 'ABCDEFG'[-2:-6:-1]
'FEDC'
# 反转字符串
>>> 'ABCDEFG'[::-1]
'GFEDCBA'

参考:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756919644a792ee4ead724ef7afab3f7f771b04f5000

你可能感兴趣的:(切片)