Indexing and slicing

Working with Text, lesson 2 of 5

🔤 Working with Text, lesson 2 of 5

Indexing and slicing

Pick out single characters and substrings by position.

10 min

2 exercises

2 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

Every character in a string has a position called an index. Indexes start at 0, and negative indexes count from the end, starting at -1. Use square brackets to get one character: word[0].

Walkthrough

Two ways to count: word = "Python"

index012345wordPythonfrom end-6-5-4-3-2-1
Step 1 of 5

Every character has two indexes: one counting from 0 at the front, and a negative one counting from -1 at the back.

the index you ask for
the character you get
Example

Single characters

Try word[6]. There is no index 6, so Python raises an IndexError.

Quiz

What does this print?

A slice text[start:stop] takes the characters from start up to, but not including, stop.

  • Leave out start to begin at the start: text[:3]
  • Leave out stop to go to the end: text[3:]
  • Negative indexes work too: text[-3:] is the last 3 characters
  • Add a step: text[::2] takes every 2nd character, and text[::-1] reverses the string
Walkthrough

Slicing word = "Python"

Python012345word[0:2]startstop
Step 1 of 6
result = 'Py'

Start at index 0 and stop before index 2. The slice has 2 - 0 = 2 characters.

in the slice
stop: not included
Example

Slices

With the default step of 1, non-negative indexes, and start <= stop <= len(word), a slice has stop - start characters: word[2:5] has 3. The shortcut breaks for steps, negative indexes, and a stop past the end — word[::2] has 3 characters, not 6 - 0 = 6, and word[3:10] has 3, not 7 — so count (or use len()) there.

Quiz

What does this print?

Exercise

Slice it up

Using indexes and slices of word, set:

  • first to the first letter
  • last to the last letter
  • middle to everything except the first and last letters
Exercise

Palindrome peek

Store word reversed in backwards using a slice. (A palindrome reads the same both ways, like "racecar". Try other words after checking!)