Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over character in string with index [duplicate]

Tags:

python

Let me explain my problem with a real life code example:

message = "hello"
for char in message:
    print(char)

This program output is:

h
e
l
l
o

But i want to know character position. when i use str.index() it become:

message = "hello"
for char in message:
    print(char, message.index(char))

Output:

h 0
e 1
l 2
l 2
o 4

The L position is 2, and not 2 and 3! How can i get character position while iterating over this message?

like image 358
Exind Avatar asked Dec 17 '22 14:12

Exind


1 Answers

.index() finds the first index of an element in the given list. If it appears multiple times, only the first occurrence is returned.

If you want to get pairs of elements and their respective indexes, you can use the built-in function enumerate():

for idx, char in enumerate(message):
    print(char, idx)
like image 165
Green Cloak Guy Avatar answered Dec 31 '22 20:12

Green Cloak Guy