Iterating Through a String in Python

A string in Python is a sequence of characters, meaning you can access each character one by one — using a loop (like for or while).

You can think of it like:
“Visit each character in the string, one at a time.”

1. Using a for Loop (Most Common Way) The for loop automatically takes each character in the string one by one.

Example: Simple iteration.

Python

text = "Python"

for char in text:
    print(char)

Output:

P
y
t
h
o
n      

Explanation

2. Using for Loop with Index (range()) If we also want to know index positions, use range(len(string)).

Python

text = "Python"

for i in range(len(text)):
    print(f"Index {i} → {text[i]}")

Output:

Index 0 → P
Index 1 → y
Index 2 → t
Index 3 → h
Index 4 → o
Index 5 → n

Explanation

3. Using enumerate() The enumerate() function gives both index and character in each loop automatically.

Example:

Python

text = "Python"

for index, char in enumerate(text):
    print(f"Index {index}: {char}")

Output:

Index 0: P
Index 1: y
Index 2: t
Index 3: h
Index 4: o
Index 5: n 

Key Takeaways