Please enable JavaScript to use CodeHS

Python Tutorial

Indexing Python Strings

Every character in a string has a numbered slot, like a wall of hotel mailboxes. Learn to read those numbers, count from the front or the back, and fetch exactly the character you want.

python ~20 min Beginner friendly
The Big Idea

Strings are sequences

In the Python Strings tutorial, we saw that every string is made up of a finite number of characters. Now let's look a little deeper at what sits between the quotation marks, because Python gives every single character its own numbered position, and that lets you reach in and grab exactly the one you want.

Take a moment to look at this string: "I'm a string!"

The syntax is fairly straightforward: several letters and one exclamation point. But something that isn't obvious at first is the spaces. In English, words are separated with spaces to signal a small pause before the next word. Without them you could probably still decipher what is being said, but it would take a moment:

"Thisisastring!"

We'd call that example mechanically incorrect. To "speak" Python's language properly, you include what is known as whitespace: the blocks or spaces between characters, created with the tab, return, or space bar on your keyboard. Here's the key fact for this tutorial: even though whitespace looks like emptiness, Python still counts it. A space is a character, and it gets a numbered slot just like every letter.

Key word: an index is the location of a particular item within a data set. In a string, every character (whitespace included!) has one.

Counting Forward

Positive index numbers

Because a string is a finite sequence of characters, the program reads each character in order. Reading from left to right, the index count begins with zero and increases by one until the end of the string.

That trips a lot of people up, so here it is again: the first character lives at index 0, not 1. The string "I'm a string!" has a total of 13 characters, including the whitespaces, but because counting starts at zero, the index numbers only go up to 12.

Say we want to grab the "a" and print it on the screen. We count from zero and record the number that lands on "a": that's index 4 (the space at index 3 counts!). Then we put that number in square brackets right after the string's name:

main.py
issa_string = "I'm a string!"

# I=0  '=1  m=2  space=3  a=4 ...
print(issa_string[4])
Console
a

The first and last slots

Since counting starts at 0, the last index is always one less than the string's length. The len() function tells you the length, so s[len(s) - 1] always fetches the final character, no matter how long the string is:

main.py
word = "mailbox"

print(word[0])              # the FIRST character
print(len(word))            # 7 characters...
print(word[len(word) - 1])  # ...so the last slot is 6
Console
m
7
x

Remember: a string with 13 characters has indexes 0 through 12. Length and last index are always exactly one apart.

When It Breaks

Off the end: IndexError

What happens if you ask for a slot that doesn't exist? "I'm a string!" ends at index 12, so asking for index 13 is like asking the bellhop to open mailbox 13 on a wall that only has slots 0 through 12. Python doesn't shrug it off, it stops your program with an IndexError:

main.py
issa_string = "I'm a string!"
print(issa_string[13])   # there is no slot 13!
Console
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(issa_string[13])
IndexError: string index out of range

Read the last message from the bottom up: the error type is IndexError, and the reason is string index out of range. Whenever you see it, check your counting: did you forget that indexes start at zero, or that spaces count too?


Counting Backward

Negative index numbers

There is another method for accessing a character, and it comes in handy for characters placed toward the end of a lengthy string. Instead of counting from the left, you read from right to left, starting with -1 (there's no such thing as negative zero, so the back door starts at -1).

To access the same letter "a" in "I'm a string!", we would use -9 instead of 4:

main.py
issa_string = "I'm a string!"

# !=-1  g=-2  n=-3 ... counting from the back
print(issa_string[-9])
Console
a

Since "a" sits near the center of the string, a negative index doesn't make that grab any easier. But reaching the punctuation mark at the very end? That's where negative indexing shines: issa_string[-1] is always the last character, even if the string grows or shrinks.

Two keys, one mailbox: every character has both a positive and a negative index. In a string of length 13, index 4 and index -9 open the same slot, because 4 - 13 = -9.


Interactive

The index inspector

Time to get hands-on. Type any word or phrase into the inspector and every character gets its own mailbox slot, with its positive index on the brass plate above and its negative index below. Then look up any index (negative ones too!), or flip to Find the index mode and prove you can count like Python.

Index Inspector

Your string

s = ""
positive index (from the front) negative index (from the back)
s[ ]
Result

Which index fetches the glowing character?

s[]

Try this: look up an index past the end of your string, then try -1. And in Find mode, remember: both the positive and the negative index count as correct.


Putting It To Work

Using indexed characters

An indexed character isn't just for printing. s[i] hands you a regular one-character string that you can store in a variable, glue onto other strings, or pass into functions and methods.

For example, you can build someone's initials by plucking two characters and concatenating them:

main.py
name = "Grace Hopper"

# index 0 is the G, index 6 is the H (the space is index 5!)
initials = name[0] + name[6]
print(initials)
Console
GH

Here's the trick from the original tutorial. Python has a string method called strip(), which removes whatever character you pass it from the ends of a string. Pass it issa_string[-1], the exclamation point we grabbed with a negative index, and you get a new, unexcited version of the string. We'll name the new variable drab:

main.py
issa_string = "I'm a string!"
drab = issa_string.strip(issa_string[-1])
print(drab)
Console
I'm a string
Full Program

Try it out

To recap: strings are made of a finite number of characters in sequential order, and every character, including each block of whitespace, is assigned an index. You can count those indexes with positive numbers from the front or negative numbers from the back, and print the appropriate item onto the screen.

Here's the complete Drab program from the original tutorial. Run it, then see if you can predict what would change if you swapped -1 for another index:

main.py
'''
This program prints the same string with
and without the exclamation point
'''

# This is the original string
issa_string = "I'm a string!"
print(issa_string)

print("Let's remove the '!'")

# This function removes the !, then prints
drab = issa_string.strip(issa_string[-1])
print(drab)
Console
I'm a string!
Let's remove the '!'
I'm a string

Vocabulary check. Before the practice problems, see if you can define each of these on your own: string, whitespace, and index. (Practice challenge 1 has the answers.)


Your Turn

Practice challenges

Test your counting skills, then reveal each answer to check yourself. The index inspector above makes a great scratchpad.

1

Vocabulary check

In your own words, define: string, whitespace, and index.

A string is a finite sequence of characters between quotation marks. Whitespace is the blocks or spaces between characters, made with the tab, return, or space bar, and Python counts it like any other character. An index is the location of a particular item within a data set, like a character's numbered position in a string.

2

Two keys, one letter

In issa_string = "I'm a string!", give two different index numbers that both make print(issa_string[...]) output the letter a.

4 counting from the front (I=0, '=1, m=2, space=3, a=4) and -9 counting from the back. They open the same slot: with 13 characters, 4 - 13 = -9.

3

Predict the program

Without running it, figure out exactly what this program prints. Careful with the space and the counting!

snack = "hot dog"
print(snack[3])
print(snack[-1])
print(snack[len(snack) - 2])

Line by line: snack[3] is the space (h=0, o=1, t=2, space=3), so the first print outputs a blank. snack[-1] is g, the last character. len(snack) is 7, so snack[5] is o. The console shows an empty first row, then g, then o.

solution.py
snack = "hot dog"
print(snack[3])              # the space!
print(snack[-1])             # last character
print(snack[len(snack) - 2]) # 7 - 2 = index 5
Console
g
o
4

Fix the crash

Amara wants to print the last character of any password. Her program crashes with IndexError: string index out of range. What went wrong, and what are two ways to fix it?

password = "hunter2"
print(password[len(password)])

len(password) is 7, but the 7 characters live in slots 0 through 6, so slot 7 doesn't exist. Fix it with password[len(password) - 1], or even better, count from the back: password[-1].


Check Yourself

Quick quiz

1. What does print("python"[1]) output?

2. With s = "code rocks", what is s[4]?

3. With word = "index", what does print(word[-2]) output?

Keep learning Python

You can fetch any single character from the front or the back of a string. Next up: slicing, which grabs whole chunks of a string at once using the same index numbers.