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
- On 1st iteration → char = 'P'
- On 2nd iteration → char = 'y'
- …
- On 6th iteration → char = 'n'
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
- range(len(text)) → gives [0, 1, 2, 3, 4, 5]
- We use text[i] to access each character by index.
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
- Strings are iterable in Python.
- The for loop is the easiest and most common way.
- Use enumerate() when you need both index and character.
- Strings are immutable, but you can iterate and create new strings based on conditions.