Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Search substring in a string and get index of all occurances

Reply
Thread Tools

Search substring in a string and get index of all occurances

 
 
Nico Grubert
Guest
Posts: n/a
 
      06-21-2006
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
 
Reply With Quote
 
 
 
 
Pierre Quentel
Guest
Posts: n/a
 
      06-21-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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
All occurances of a character in a string Raghu Go Ruby 10 04-30-2008 07:02 PM
replace multiple occurances of string with a single string ranumehta79@gmail.com Java 1 07-31-2006 11:57 AM
RegEx search for a substring within a substring colinhumber@gmail.com Perl Misc 3 08-03-2005 04:29 PM
RegEx: find all occurances of a single character in a string Franz Steinhaeusler Python 9 12-15-2004 11:06 AM
Counting occurances of string A in string B, and adding it to string B Sandman Perl Misc 7 08-03-2004 08:46 PM



Advertisments