Slices

slice objects

A slice object can be passed in place of an index.

cut = slice(4, 11)
text = "The unknown unknown"

text[cut]
'unknown'

Useful in processing strings.

field_1 = "Bananas, oranges      101 134,23  £11,23"
field_2 = "Apples, pineapples    102 234,53  £14,13"
field_3 = "Kiwi fruit            103  13,03   £2,99"

DESCRIPTION = slice(0, 22)

print(field_1[DESCRIPTION])
print(field_3[DESCRIPTION])
Bananas, oranges      
Kiwi fruit

Assigning to slices

a = list(range(7))
a
[0, 1, 2, 3, 4, 5, 6]
a[2:4] = [12, 14]
a
[0, 1, 12, 14, 4, 5, 6]
del a[4:]
a
[0, 1, 12, 14]

If you spot any errors please let me know on twitter.