• Index

### 关于作者

#### 切片

>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']


>>> [L[0], L[1], L[2]]
['Michael', 'Sarah', 'Tracy']


>>> r = []
>>> n = 3
>>> for i in range(n):
...     r.append(L[i])
...
>>> r
['Michael', 'Sarah', 'Tracy']


>>> L[0:3]
['Michael', 'Sarah', 'Tracy']


L[0:3]表示，从索引0开始取，直到索引3为止，但不包括索引3。即索引012，正好是3个元素。

>>> L[:3]
['Michael', 'Sarah', 'Tracy']


>>> L[1:3]
['Sarah', 'Tracy']


>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']


>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]


>>> 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]


>>> L[:]
[0, 1, 2, 3, ..., 99]


tuple也是一种list，唯一区别是tuple不可变。因此，tuple也可以用切片操作，只是操作的结果仍是tuple：

>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)


>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'


### 练习

# -*- coding: utf-8 -*-
def trim(s):
----
return s
----
# 测试:
if trim('hello  ') != 'hello':
print('测试失败!')
elif trim('  hello') != 'hello':
print('测试失败!')
elif trim('  hello  ') != 'hello':
print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim('    ') != '':
print('测试失败!')
else:
print('测试成功!')


do_slice.py