PyPyPath

Module 4: Strings in Python

Indexing Strings

Each character in a string has a position called an index. Python counts from 0 — the first letter is index 0.

About 8 minutes

Indexes in "Python"

P

index 0

y

index 1

t

index 2

h

index 3

o

index 4

n

index 5

Example code
word = "Python"
print(word[0])   # P
print(word[1])   # y
print(word[-1])  # n (last character)

Negative indexes count from the end: -1 is last, -2 is second-to-last.

Practice

For text = "Data", print the first char, third char, and last char (use -1).

Key takeaways

  • Indexes start at 0.
  • Use text[i] to get one character.
  • Negative indexes count from the end.

Quick check: Indexing Strings

Question 1 of 2

What is word[0] when word = "cat"?