Search substring in a string and get index of all occurances

Discussion in 'Python' started by Nico Grubert, Jun 21, 2006.

  1. Nico Grubert

    Nico Grubert Guest

    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
    Nico Grubert, Jun 21, 2006
    #1
    1. Advertising

  2. 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
    Pierre Quentel, Jun 21, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Franz Steinhaeusler
    Replies:
    9
    Views:
    489
    Fredrik Lundh
    Dec 15, 2004
  2. Raghu Go
    Replies:
    10
    Views:
    229
    Adam Shelly
    Apr 30, 2008
  3. Sandman
    Replies:
    7
    Views:
    190
    Anno Siegel
    Aug 3, 2004
  4. Replies:
    3
    Views:
    190
    Sherm Pendley
    Aug 3, 2005
  5. Replies:
    3
    Views:
    91
    John W. Krahn
    Sep 16, 2007
Loading...

Share This Page