runtime
27 / 250
lesson 27 Strings & Text · beginner

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.

You'll be able to
  • 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
The idea

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.

example-1.py · Pieces of a timestamp
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.

example-2.py · Masking a card number
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 only 0.
  • Mixing up text[-4:], the last four characters, with text[:-4], everything except the last four.
Review
  • text[start:end] includes start and stops before end. Leave either one out to run to that end.
  • text[-n:] is the last n characters, and text[:-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.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Take a piece — Strings & Text · Runtime