Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.1 — Indexing and Slicing
Python · Example 1 of 3

Indexes count from zero

Predict each line before you run it. Then change the word and run again.

Every character in a string has a position number, starting at 0, and you can also count from the end with negative numbers. A slice s[start:stop:step] cuts out a piece of the string, never fails for out-of-range numbers, and gives you a new string.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given word = "Hectal", print its first three letters, its last three letters and the word reversed.

02

Given s = "0123456789", print every third character starting from index 1.

03

Given email = "user@example.com", find the position of @ with email.find("@") (find gives the index of the first match; Topic 3.2 teaches it) and print the part after it and the part before it.

Explain it without notes

01

Why do Python indexes start at 0, and what is the last valid index of a string?

02

What does s[a:b] return, and why is b excluded?

03

Explain how s[::-1] reverses a string, and what changes about the defaults when the step is negative.

04

What is the difference between s[10] and s[10:11] when s is shorter than 10 characters?

Indexes count from zero
Sign in to run this example in your browser.

Expected output

word: Python
first letter: P
second letter: y
last letter: n
second from the end: o
length: 6
last, counted from the front: n