1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Indexing & slicing

A string is a row of characters. Each one has a position called its index, and counting starts at 0:

0P-10
1y-9
2t-8
3h-7
4o-6
5n-5
6i-4
7s-3
8t-2
9a-1
  • word[0] is the first character, word[-1] the last
  • word[2:6] is a slice: from index 2 up to, not including, 6
  • word[::-1] steps backwards, which reverses the string
  • len(word) is the number of characters

An omitted slice start means "from the beginning": word[:2]. An omitted stop means "to the end": word[-4:]. Multiplying text repeats it: "*" * 3 gives "***".

See it run

word = "planet"
i = 0
i = 3
i = -1
part = word[1:4]

Each letter sits in its own numbered cell, counting from 0. The highlight follows word[i].

Practice indexing & slicing

Exercise 1

With word = "Pythonista" create:

  • first = the first character
  • last = the last character (use a negative index)
  • middle = "thon" (a slice)
  • backwards = the reversed word

Exercise 2

A shop's product codes look like UK-2026-BLUE. Use slices of code to make:

  • country = the first 2 characters ("UK")
  • year = the 4 digits in the middle, as an int (2026)
  • colour = the last 4 characters, using a negative slice ("BLUE")

Exercise 3

Receipts must hide the card number in the code editor below except its last 4 digits.

  • last4 = the last 4 characters of card
  • masked = one * for every other digit, followed by last4 (************4444)

Use len(card) so it also works for cards of a different length. The check will try a 15-digit card too.

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest