Iterate through string Python | Example code

Using the for loop construct can Iterate through the string in Python. If you need access to the index as you iterate through the string, use enumerate() function.

Examples Iterate through string Python

Simple example code.

Using for-loop

for c in "string":
    print(c)

Output:

Iterate through string Python

Use enumerate() function

Get index and char values. Iterate over character in a string with index.

for i, c in enumerate('Hello'):
    print(i, c)

Output:

0 H
1 e
2 l
3 l
4 o

Do comment if you have any doubts and suggestions on this Python iterate topic,

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.