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. Advertisements

  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. Advertisements

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:
    629
    Fredrik Lundh
    Dec 15, 2004
  2. Replies:
    1
    Views:
    758
    =?iso-8859-1?q?Fl=E1vio_Barata?=
    Jul 31, 2006
  3. Timur Tabi
    Replies:
    4
    Views:
    1,294
    Timur Tabi
    Oct 14, 2009
  4. Raghu Go
    Replies:
    10
    Views:
    353
    Adam Shelly
    Apr 30, 2008
  5. Sandman
    Replies:
    7
    Views:
    435
    Anno Siegel
    Aug 3, 2004
  6. Replies:
    3
    Views:
    382
    Sherm Pendley
    Aug 3, 2005
  7. deadpickle
    Replies:
    0
    Views:
    114
    deadpickle
    Feb 8, 2007
  8. Replies:
    3
    Views:
    160
    John W. Krahn
    Sep 16, 2007
Loading...