Slices

slice objects

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

In [14]:
cut = slice(4, 11)
text = "The unknown unknown"

text[cut]
Out[14]:
'unknown'

Useful in processing strings.

In [15]:
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

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