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?
.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With