Python Find indexes of specific character in a string


How to list all indexes of specific character in a string.

Usually index() returns first position of occurrence of specified character  but there's a way to get all indexes of what you're looking for.

Python: How to find all indexes of specific character in a string


Let's say we want to have indexes of $ in a string that's:
k = '0213sada$da1dgf3$2000sfdsfsdffs$gfgerg'
We'll use index() which has syntax: string.index(value, start), with start you can define from which index to start indexing the value.

k = '0213sada$da1dgf3$2000sfdsfsdffs$gfgerg'

position = 0
res = []

while True:
try:
position = k.index('$',position)
except ValueError:
break
res.append(position)
position +=1

print(res)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

[8, 16, 31]
First we need define position variable with value 0 which will change to value index of each "$". In infinite while loop create Try/Except block and under Try statement:
position = k.index('$',position)
This line means seek for $ position from previous "$" position.

Index() raises a ValueError when element is not found that why we catch exeception with:
except ValueError:
break
The next two lines are adding the position of "$" and changing position variable to present value index.
    res.append(position)
position +=1

Comments