Explain Codes LogoExplain Codes Logo

Iterating each character in a string using Python

python
iterators
string-manipulation
python-features
Nikita BarsukovbyNikita Barsukov·Nov 14, 2024
TLDR

Here's how to quickly iterate through a string's characters using a for loop:

for char in "abc": print(char)

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:

for index, char in enumerate("Python"): print(f"Position {index} in line, sir! Character '{char}' reporting!")

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:

i = 0 s = "Hello" while i < len(s): print(f"Letter on index {i} is '{s[i]}' - recruited by 'while'") i += 1

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!

class CustomIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index == len(self.data): raise StopIteration char = self.data[self.index] self.index += 1 return char for char in CustomIterator("abc"): print(char)

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!

for char in "naïve café": print(f"Critical character inspection reveals: {char}")

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:

for char in "Hello": # Trying this rebellious act will NOT change the original string char = 'A' print(char)

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.