Iterating each character in a string using Python
Here's how to quickly iterate through a string's characters using a for
loop:
This outputs every character: a
, b
, and c
.
Deep-dive example
A for loop is the most common and simplest way of iterating over each character in a string. This method is in line with Python's inherent iterator protocol.
Enumerating your string
When you also want the index along with the character in your string, use the enumerate()
function to accomplish this:
No need to get len()
involved or manually track indexes, enumerate()
got it covered!
The while alternative
While certainly not the belle of the ball, a while
loop can also step up for string iteration duty:
However, Pythonistas generally prefer the elegance, readability, and just plain coolness of for loops.
Your own iterator, because why not
Feeling bold? You can customize string iteration by making your own iterator, just because you can!
This prints the same result as the for loop, but with added complexity for flavor.
Unicode? More like funicode!
Python strings can contain Unicode characters, so you might come across instances where one character is actually a blend of multiple code points. Beware the element of surprise!
String alteration during iteration
Remember, though, trying to alter a string within a for loop is like asking a fish to climb a tree - it's just not going to work because strings in Python are immutable:
Any changes like this would require the creation of a new string.
Beware the iteration pitfalls
Like every other coding process, trying to iterate over a string using the wrong or less efficient methods can lead to pitfalls:
- Syntax errors from using incorrect brackets.
- Classic off-by-one errors, since we always tend to forget indexes start at 0.
- String immutability can bite you. You can't just change characters in a string willy-nilly.
Was this article helpful?