Iterating over strings

Published

2023-07-31

Iterating over strings

We’ve seen how we can iterate over sequences such as lists, tuples, and ranges. Python allows us to iterate over strings the same way we do for other sequences!

When we iterate over a string, the iterator returns one character at a time. Here’s an example:

>>> word = "cat"
>>> for letter in word:
...    print(letter)
...
c
a
t

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).