LightMySky

Strings: Indexing, Slicing and Length

Treating text as a sequence of characters that can be measured, indexed from zero, and cut into parts.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Get the first, last and middle characters of a string
  • Take a slice and predict exactly where it starts and stops
  • Use the length of a string inside a loop or a condition

1 · Read

Think of a string as a row of characters, each with its own seat number. The first character sits at seat 0, the next at 1, and so on. You write name[0] to grab the character in seat 0.

Try it together

A phone number is just text, so you can slice it. If phone holds 02079460018, then phone[0:3] copies seats 0, 1 and 2, giving 020. A slice starts at its first number and stops just before its last number.

len() counts every character: letters, digits, spaces and all. You can use that count in a loop or a test, for example to walk each seat in turn. The last seat is always one below the length, and name[-1] grabs it directly.

Good to know

Off-by-one slips love index code, one seat too high or too low. Always check the output against the seats you meant.

Count seats from zero, slice from the start up to the stop, and measure with len().

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Strings: Indexing, Slicing and Length · Computing, ages 15 to 16 · LightMySky