In Python, slice(start, stop, step) creates a slice object that describes a range of positions. seq[slice(1, 6, 2)] is the same as seq[1:6:2]. With one argument, slice(stop) starts at the beginning.
Slice objects let you name and reuse a slice, which makes code that cuts fixed-width text much easier to read. They expose .start, .stop, and .step, and indices(length) converts them into concrete numbers for a sequence of that length.
slice is a built-in type (a class) that you call like a function: each call creates a new slice object. Like every built-in, it lives in the builtins module and is always available without an import.
Syntax
Create a slice, then use it inside square brackets.
One argument is stop.slice(3) means [:3], the first three letters.
Step of 2.slice(0, None, 2) takes every other letter from the start.
Negative start.slice(-2, None) keeps the last two letters.
Readable repr. Printing a slice shows all three parts, and it matches the colon syntax exactly.
Example 2 — Parse Fixed-Width Records with Named Slices
Give each column of a fixed-width line a name and reuse it for every record.
python
records = [
"2024-03-09 Ana 42",
"2024-03-10 Ben 108",
]
DATE = slice(0, 10)
NAME = slice(11, 16)
SCORE = slice(16, 19)
for line in records:
print(line[DATE], line[NAME].strip(), int(line[SCORE]))
Output
2024-03-09 Ana 42
2024-03-10 Ben 108
How It Works
Columns by position. The date is characters 0 to 9, the name 11 to 15, and the score 16 to 18.
Named once.DATE, NAME, and SCORE document the layout better than bare numbers.
Clean the pieces.strip() drops padding from the name and int() ignores the leading space of " 42".
Same slices, every line. The loop applies the stored slices to each record.
Example 3 — Inspect a Slice with indices()
Read a slice's parts and resolve them for a concrete length, including a reversing slice.