Search substring in a string and get index of all occurances

Pierre Quentel quentel.pierre at wanadoo.fr
Wed Jun 21 04:35:20 EDT 2006


mystring = 'John has a really nice powerbook.'
substr = ' '  # space

pos = 0
indices = []
while True:
    i = mystring.find(substr,pos)
    if i==-1:
        break
    indices.append(i)
    pos = i+1
print indices
> [4, 8, 10, 17, 22]

Pierre




More information about the Python-list mailing list