0
0
PythonHow-ToBeginner · 3 min read

How to Iterate Over String in Python: Simple Guide

To iterate over a string in Python, use a for loop to access each character one by one. The syntax is for char in string: where char represents each character during the loop.
📐

Syntax

The basic syntax to iterate over a string uses a for loop. You write for char in string: where string is your text and char is each character you get one at a time.

Inside the loop, you can use char to work with each character.

python
for char in string:
    # do something with char
💻

Example

This example shows how to print each character of a string on its own line using a for loop.

python
my_string = "hello"
for char in my_string:
    print(char)
Output
h e l l o
⚠️

Common Pitfalls

One common mistake is trying to use a for loop without specifying the string variable, or trying to access characters by index without a loop.

Another is modifying the string inside the loop, which is not allowed because strings are immutable in Python.

python
wrong_string = "hello"
# Wrong: trying to change characters directly
for char in wrong_string:
    char = char.upper()  # This does not change the original string

# Right way: build a new string
new_string = ""
for char in wrong_string:
    new_string += char.upper()
print(new_string)
Output
HELLO
📊

Quick Reference

Remember these tips when iterating over strings:

  • Use for char in string: to get each character.
  • Strings cannot be changed directly; create a new string if needed.
  • You can use enumerate(string) to get both index and character.

Key Takeaways

Use a for loop with for char in string: to iterate over each character.
Strings are immutable; you cannot change characters directly inside the loop.
Build a new string if you want to modify characters during iteration.
Use enumerate(string) to get both index and character if needed.