Course outline · 0% complete

0/32 lessons0%

Course overview →

Indexing and Slicing

lesson 2-1 · ~12 min · 4/32

Quiz

Warm-up from lesson 1-3: you learned that `/` behaves differently from `//`. What is the type of the result of `10 / 5`?

A string is a sequence of characters

Almost everything a program receives from the outside world arrives as a string: usernames, file names, dates, whole files. Pulling pieces out of them, the year from "2026-07-06", the extension from "report.pdf", is daily work for any engineer, and indexing and slicing are the tools that do it.

Every character in a string has a numbered position called an index. Counting starts at 0, not 1. You read one character with square brackets, and len() tells you how many characters there are.

word = "Python"
#       P  y  t  h  o  n
#       0  1  2  3  4  5

Negative indexes count from the end: word[-1] is the last character, word[-2] the one before it. That saves you from writing word[len(word) - 1].

Asking for an index that does not exist, like word[6] here, stops the program with an IndexError.

Python012345-6-5-4-3-2-1index
Indexes for "Python": 0 to 5 from the front, -1 to -6 from the back. The pointer steps through each position.

Code exercise · python

Run this and match each line to the diagram above.

Slicing: grabbing a piece

A slice copies a range of characters: word[start:stop] takes from index start up to but not including stop.

word = "Python"
word[0:2]   # "Py"   indexes 0 and 1
word[2:6]   # "thon"

Leave a side empty and Python fills in the edge: word[:2] means from the start, word[2:] means to the end. A handy way to read s[:n] is "the first n characters".

Slices never fail with an error. word[2:100] just stops at the end and gives "thon".

Code exercise · python

Your turn. Using slices only (no retyping the letters), print the first 3 characters of `keyboard` on one line and the rest on the next line.

Code exercise · python

One more, on real data. `date` holds a date in YYYY-MM-DD form. Slice out the year, the month, and the day, and print each on its own line. Count carefully: the dashes sit at indexes 4 and 7.