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:

 P  y  t  h  o  n
 0  1  2  3  4  5
-6 -5 -4 -3 -2 -1

Use square brackets to get one character: word[0].

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:]
  • Add a step: text[::2] takes every 2nd character, and text[::-1] reverses the string
Example

Slices

The length of a slice is stop - start: word[2:5] has 3 characters.

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!)