Python 提供了一种把序列切成小块的方法。
针对内置的 list、str 和 bytes 的切割。
list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# index = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# index = -0(-10),-9,-8,-7,-6,-5,-4,-3,-2,-1
[start_index:end_index]
print(list_num[:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(list_num[1:4])
# index-123 [2, 3, 4]
print(list_num[2:])
# index-2... [3, 4, 5, 6, 7, 8, 9, 0]
print(list_num[:8])
# index-...7 [1, 2, 3, 4, 5, 6, 7, 8]
print(list_num[7:2])
# if start_index > end_index []
print(list_num[-4:-2])
# index~-4,-3 [7, 8]
print(list_num[-4:])
# index~-4... [7, 8, 9, 0]
print(list_num[-0:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(list_num[-12:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(list_num[-1:0])
# if start_index > end_index []
print(list_num[-1:-1])
# []
print(list_num[-1:])
# [0]
print(list_num[-12:6])
# [1, 2, 3, 4, 5, 6]
c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
c1, c2 = c[2:4]
print(c1, c2)
# 3 4
c3, c4 = c[5:8]
print(c3, c4)
# ValueError: too many values to unpack (expected 2)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
a[2:4] = ['a', 'b', 'c', 'd']
print(a)
# index_start: 2 扩张
# [1, 2, 'a', 'b', 'c', 'd', 5, 6, 7, 8, 9, 0]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b[2:7] = ['123','456']
print(b)
# index_start: 2 缩减
# [1, 2, '123', '456', 8, 9, 0]