0
How can I found the element's index in the string
For example: a = "XKLMN" for i in a: if (i == "M"): print(" index of 'M' is : ")
3 Answers
+ 3
a = "XKLMN"
print(a.find('M')) # returns -1 if the value is not found.
print(a.index('M')) # raises an exception if value not found.
+ 4
a = "MXKLMN"
x = 'M'
You can use index(), but if the desired character can not be found, a ValueError will be raised, and the program will be terminated. you could avoid this with a try... except block:
print(a.index(x))
Or you use find(), that also gives an index back, but does not cause an error if the desired character cannot be found. In this case it returns -1:
print(a.find(x))
Or let's assume we have a string, that may contain more than one of the desired character. So var "a" contains 2 x "M":
print(*[i for i, e in enumerate(a) if e == x])
In this last example you will get all index positions of the desired character back
+ 2
Create a counter variable assigned to zero and increase it by one each iteration.
edit:
or
print (a.index ('M'))