How to Iterate Over a String in Python: Simple Guide
To iterate over a string in Python, use a
for loop to go through each character one by one. Each loop cycle gives you one character from the string, which you can use inside the loop.Syntax
Use a for loop followed by a variable name and the string you want to loop over. The variable holds each character in the string during each loop cycle.
for: starts the loop- variable: stores the current character
- string: the text you want to iterate
python
for character in string: # do something with character
Example
This example shows how to print each character of the string "hello" on a new line using a for loop.
python
string = "hello" for character in string: print(character)
Output
h
e
l
l
o
Common Pitfalls
One common mistake is trying to use a for loop without specifying the string or using incorrect indentation. Another is trying to change characters directly inside the loop, which is not allowed because strings are immutable.
Wrong way example:
for character in string:
character = 'x' # This does not change the original stringRight way example:
new_string = ""
for character in string:
new_string += 'x' # Builds a new stringQuick Reference
Remember these tips when iterating over strings:
- Use
for char in string:to loop through characters. - Strings cannot be changed directly; create a new string if needed.
- Indentation matters inside the loop.
Key Takeaways
Use a for loop to access each character in a string one by one.
Strings are immutable; you cannot change characters directly inside the loop.
Indent your code properly inside the loop to avoid errors.
Build new strings if you want to modify characters during iteration.