Python Arena
Step 3 of 6

One character at a time

A string is a row of characters, and each character has a number that tells its place: its index. Indexes start from 0, not 1. The first character has the index 0, the second has 1, and so on:

p  y  t  h  o  n
0  1  2  3  4  5

To get a single character, write its index in square brackets after the string:

word = "python"
print(word[0])
print(word[1])
print(word[5])
Output
p
y
n

The result is a string too, one character long, so you can join it, compare it and print it like any other string.

The last character

A string of 6 characters has the indexes 0 to 5: the last index is always one less than the length. So for a string of any length, the last character is at len(text) - 1.

In a word chain game, each word must start with the letter the previous word ended with. This program checks one link of the chain, comparing the first character of the new word with the last character of the old one:

old = input("Previous word: ")
new = input("Your word: ")
if new[0] == old[len(old) - 1]:
    print("Good link!")
else:
    print("Your word should start with " + old[len(old) - 1])
Input
python
apple
Output
Previous word: python
Your word: apple
Your word should start with n

IndexError

Asking for an index that the string doesn't have stops the program. A very common slip is to use the length itself as the last index:

word = "cat"
print(word[len(word)])
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(word[len(word)])
          ~~~~^^^^^^^^^^^
IndexError: string index out of range

"cat" has the indexes 0, 1 and 2, and len(word) is 3. "Out of range" means the index is outside the indexes the string has.

Every character in turn

With a helper variable as the index, a loop can visit the characters one by one. It goes on while the index is below the length, so the last round has the index len(word) - 1:

word = "loop"
index = 0
while index < len(word):
    print(f"{index}: {word[index]}")
    index += 1
Output
0: l
1: o
2: o
3: p

Your task

Challenge 1 of 3

Fill in the blanks so the program prints the initials of the name typed in, each followed by a dot.

First name: Ada
Last name: Lovelace
A.L.

Challenge 2

Write a program that asks for a word and prints its characters one per line, each with its place in the word, counted from 1.

Word: cat
1. c
2. a
3. t

Challenge 3

This program should print every character of a word twice, one pair per line, but it stops with an IndexError. Fix it.

Word: cat
cc
aa
tt