Search substring in a string and get index of all occurances

N

Nico Grubert

Hi there,

I would like to search for a substring in a string and get the index of
all occurances.

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

I would like to get this list:
[4, 8, 10, 17, 22]

How can I do that without using "for i in mystring" which might be
expensive for large strings?

Thanks in advance,
Nico
 
P

Pierre Quentel

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top