Join Regular Classroom : Visit ClassroomTech

enumerate() in Python String

It is a method in python that iterates through the string, adds a counter to it and returns an object. The object can be converted to list or tuple later.

Syntax:

enumerate(iterable, starting_position)

Example 1:

s = “Code,eat,repeat”
x = enumerate(s)
print(x)
print(list(x))

Output:


[(0, ‘C‘), (1, ‘o‘), (2, ‘d‘), (3, ‘e‘), (4, ‘,‘), (5, ‘e‘), (6, ‘a‘), (7, ‘t‘), (8, ‘,‘), (9, ‘r‘), (10, ‘e‘), (11, ‘p‘), (12, ‘e‘), (13, ‘a‘), (14, ‘t‘)]

Explanation:

Here it returned an object, which is later converted to list. Each character of the string is iterated (‘C’, ‘o’, ‘d’ ….) and returned with a counter (0, 1, 2, 3..) inside the list as pairs.

Example 2:

s = “Code eat repeat”
x = enumerate(s)
print(x)
print(tuple(x))

Output:

((0, ‘C‘), (1, ‘o‘), (2, ‘d‘), (3, ‘e‘), (4, ‘ ‘), (5, ‘e‘), (6, ‘a‘), (7, ‘t‘), (8, ‘ ‘), (9, ‘r‘), (10, ‘e‘), (11, ‘p‘), (12, ‘e‘), (13, ‘a‘), (14, ‘t‘))

Explanation:

Each character of the string is iterated (‘C’, ‘o’, ‘d’ …) and returned with a counter (0,1,2,3..) inside the tuple as pairs .

 

You Missed
Also Checkout