Skip to content

Module 7 · Strings — topic 2 of 22

Indexing

Read individual characters by position with square brackets. Learn zero-based indexes, the last valid index, IndexError, and how to loop over positions when you need them.

Beginner 10 min read·Lesson 83 of 306 in Python Programming

Learning objectives

  • Access characters with zero-based indexes
  • Calculate the last valid index
  • Avoid and understand IndexError

Definition

Read individual characters by position with square brackets. Learn zero-based indexes, the last valid index, IndexError, and how to loop over positions when you need them.

Introduction

Each character in a string has a position number called an index. The first character is at index 0, the second at index 1, and so on. You read a character with square brackets: word[0].

Why it matters

Indexing lets you inspect specific characters: the first letter of a name for initials, a check digit at the end of a code, or the character at a position found by a search.

Detailed explanation

Think of a string as a row of numbered boxes, one character per box, with the numbering starting at zero. The index is the box number, and text[i] opens box i. Because counting starts at zero, the box number of a character is also how many characters come before it, which is why zero-based indexing turns out to be convenient for calculations.

Spaces and punctuation are characters too and occupy their own indexes. In "Hi there", index 2 is the space. Forgetting this is a common reason an index points at the wrong letter.

Python counts from zero: in "PYTHON", P is at 0, Y at 1, H at 3 and N at 5.

The last valid index is len(s) - 1. Using an index equal to or greater than the length raises IndexError: string index out of range.

Indexing returns a new string of length 1. Python has no separate character type.

Indexes must be integers; s[1.0] is a TypeError.

You can index any expression that produces a string: "hello"[1] or input()[0].

To work with both positions and characters, loop with enumerate(s) rather than range(len(s)).

Index012345
CharacterPYTHON

Syntax

Python
first = text[0]
last = text[len(text) - 1]
for position, char in enumerate(text):
pass
  • Indexes start at 0.
  • The last index is len(text) - 1.
  • enumerate gives positions and characters together.

Code examples

Reading characters

Python
word = "PYTHON"
print(word[0], word[3], word[5])
print(word[len(word) - 1])
Output
P H N
N

Out of range

Python
word = "PYTHON"
try:
print(word[6])
except IndexError as err:
print("IndexError:", err)
Output
IndexError: string index out of range

More examples

Initials and character positions

Python
full_name = "Sunita Ravi Kumar"
initials = ""
for part in full_name.split():
initials += part[0]
print("Initials:", initials)
code = "INV-2049"
for i, ch in enumerate(code):
if ch.isdigit():
print("First digit", ch, "at index", i)
break
Output
Initials: SRK
First digit 2 at index 4

Step-by-step explanation

  • split() breaks the name into three words.
  • part[0] takes the first character of each word and adds it to initials.
  • enumerate gives each character of the code with its index.
  • The loop stops at the first digit, which is at index 4.

Expected output

Running “Initials and character positions” prints exactly:

TextOutput
Initials: SRK
First digit 2 at index 4

Practical applications

  • Form processing builds initials and abbreviations from names.
  • Barcode and ID validators read characters at fixed positions.
  • Text editors track the cursor as an index into the text.

Best practices

  • Check for empty strings before indexing.
  • Use enumerate when you need positions.
  • Prefer negative indexing (next lesson) for the end of a string.

Common mistakes

Using len(s) as an index

Avoid

last = word[len(word)]

Prefer

last = word[len(word) - 1] # or word[-1]

The highest valid index is one less than the length.

Indexing an empty string

Avoid

first = name[0] # name may be ""

Prefer

first = name[0] if name else ""

An empty string has no index 0.

Key takeaways

  • Indexes start at 0 and go up to len(s) - 1.
  • s[i] returns a one-character string.
  • An index outside the range raises IndexError.

Try it yourself

  1. 1
    Print the first and third characters of your name.
  2. 2
    Loop over a word with enumerate and print each character with its index.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic