Enumerate a String
Python - Enumerate a String
In Python, enumerate() takes a string as argument and adds a counter value to the iterable: list of characters in the string.
In a For Loop, we can access the index of the characters along with the characters.
Using List Comprehension, we can convert the given string into a list of tuples, where each tuple contains the index and the respective character.
Examples
1. Iterate over Enumerated String
In this example, we will take a string, and iterate over the enumerated string (list of characters), thus accessing both index (counter value) and respective character.
Python Program
string1 = 'apple'
for index, ch in enumerate(string1):
print(index, ':', ch)
Output
0 : a
1 : p
2 : p
3 : l
4 : e
2. Convert Enumerated string into a List of Tuples
In this example, we will take a string, and create a list of tuples from this string, where each tuple contains the index and respective character from the string.
Python Program
string1 = 'apple'
result = [ch for ch in enumerate(string1)]
print(result)
Output
[(0, 'a'), (1, 'p'), (2, 'p'), (3, 'l'), (4, 'e')]
Summary
In this tutorial of Python Examples, we learned how to enumerate a string using enumerate() builtin function.