This guide explains Loop Through a String One Character at a Time through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A string is iterable, so a for loop can visit its individual Unicode code points in sequence. That does not necessarily mean each item is one visually perceived character.
When You Would Use This
Spell out a short word vertically.
Step-by-Step Example
word = "Code"
for character in word:
print(character)
How the Example Works
The loop prints C, o, d and e on separate lines. No index management is needed.
Example Output
C
o
d
e
Try It Yourself
Print each letter of your favorite four-letter word with its position using enumerate().
Common Beginner Mistakes
- Assuming every visible emoji is a single loop iteration.
- Changing the string in place during iteration; strings are immutable.
- Confusing iterating characters with iterating words separated by spaces.
Key Takeaways
- A string is iterable, so a
forloop can visit its individual Unicode code points in sequence. - The loop prints C, o, d and e on separate lines.
- Avoid this mistake: Assuming every visible emoji is a single loop iteration.