Skip to content

Python enumerate string | Example code

  • by

Using the Python enumerate function in the string, you can loop over it and will get a value with the index. The Enumerate() command adds a counter to each item of the iterable object and returns an enumerate object as an output string.

enumerate(iterable, startIndex)

Enumerate allows you to loop through a list, tuple, dictionary, or string and gives the values along with the index. This function is useful when you need to loop through a string and keep track of the current index of each character.

Python enumerate string

Simple example codes Iterating each character in a string using Python.

my_str = "HELLO"

for i in enumerate(my_str):
    print(i)

Output: the result will show you the index and value for each character of the string.

Python enumerate string

By using enumerate(), you can avoid having to manually create a counter variable and increment it for each character you process. Instead, you can simply use the for loop with enumerate() to iterate over the characters and their indices in a single line of code.

Comment if you have any doubts or suggestions on this Python enumerate topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading