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 : ")

15th May 2020, 6:36 PM
Gökhan TUNCER
Gökhan TUNCER - avatar
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.
15th May 2020, 7:05 PM
rodwynnejones
rodwynnejones - avatar
+ 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
15th May 2020, 8:01 PM
Lothar
Lothar - avatar
+ 2
Create a counter variable assigned to zero and increase it by one each iteration. edit: or print (a.index ('M'))
15th May 2020, 6:38 PM
Mustafa K.
Mustafa K. - avatar