Take a piece
A slice, text[start:end], copies the characters from start up to but not including end. Dates, prefixes and the last four digits are all slices.
- Write
text[start:end]and predict exactly which characters it includes - Leave out the start or the end, and take the last few characters with a negative start
- Explain why a slice past the end gives an empty text instead of an error
One character is often not enough. You may need the year in 2024-01-15T00:01:21.000Z, the category letters of a SKU, or the last four digits of a card. A slice, text[start:end], gives back a new text holding the characters from start up to, but not including, end.
Leave out start to begin at position 0, and leave out end to run to the end of the text. Because the end is not included, end - start is always the length of the piece, and text[:n] + text[n:] puts the whole text back together.
Run each example to see what it prints. Running examples doesn't count toward progress.
received = "2024-01-15T00:01:21.000Z" print(received[:4]) print(received[5:7]) print(received[8:10]) print(received[:10]) print(received[11:19])
A slice is forgiving where an index is not. A slice that runs past the end stops at the end, and a slice that starts past the end is empty. That makes text[-4:] safe even for a short text. It also means a wrong slice fails silently, so check your positions.
card = "4111111111111111" hidden = "*" * (len(card) - 4) print(hidden + card[-4:]) short = "4242" print("*" * (len(short) - 4) + short[-4:]) print(len(card[20:]))
When to use it: for fixed-width fields such as dates and codes, for prefixes and suffixes, and for cutting a text at a position you have found. Mistakes to avoid:
- Expecting the end position to be included.
received[5:6]is only0. - Mixing up
text[-4:], the last four characters, withtext[:-4], everything except the last four.
text[start:end]includesstartand stops beforeend. Leave either one out to run to that end.text[-n:]is the last n characters, andtext[:-n]is everything else.- A slice never raises IndexError. Past the end it is shorter, or empty.
- Next: build cleaned-up text with string methods such as strip, lower and replace.