5

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?

Exind
  • 417
  • 1
  • 6
  • 12

5 Answers5

12

.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)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

Use enumerate:

message = "hello"
for count, char in enumerate(message):
    print(char, count)
Meow
  • 1,207
  • 15
  • 23
1

Try this:

message = "hello"
for i, char in enumerate(message):
    print(char, i)
1

I adjusted your code with enumerate, this should work

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

You can find some documentation about it in the official python docs or here

Axblert
  • 556
  • 4
  • 19
1
for i,char in enumerate(message):
    print(char,i)
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
TralahM
  • 21
  • 4