Rita Sue and Bob too

Eugene Oden goden at simplified.com
Thu Aug 19 23:25:23 EDT 2004


M. Clift wrote:

> Hi All,
> 
> Can someone help. I promise I've looked how to do this but can't find a
> way...
> 
> Ok, to find one name is easy
> 
> if 'Bob' in list:
>     print "They were found"
> else:
>     print "They are not in list"
> 
> But, how to I find a sequence in a list of unknown size? i.e. this
> sequence in list of other names and replace it with three others?
> 
> 'Rita','Sue','Bob'
> 
> This is almost a nightly occurrence (my posting questions), but I am
> learning : )

here's my stab at it:

def findSequence(seq, search):
   """returns the index where search can be found in seq where search and
      seq are both sequences.
   """
   searchLength = len(search)

   for i in range(len(seq)-searchLength+1):
      compare = seq[i:i+searchLength+1]

      if search == seq[i:i+searchLength]:
         return i

   raise ValueError, 'sequence %s is not in list' % str(search)

someList = ['Joe', 'Rita', 'Sue', 'Bob', 'Peter']
searchList = ['Rita', 'Sue', 'Bob']

i = findSequence(someList, searchList)
someList[i:i+len(searchList)] = ['Paul', 'John', 'James']
# someList is now ['Joe', 'Paul', 'John', 'James', 'Peter']

findSequence(someList, searchList) # raises ValueError




More information about the Python-list mailing list