Rita Sue and Bob too
ben at benlast.com
Fri Aug 20 09:13:15 CEST 2004
> From Peter Hansen
> > 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 : )
This isn't necessarily the best way to do it generally, but it's an
Interesting problem to play with, so here's an Interesting solution. Use
the string facilities that already exist to search sequences (a string is a
sequence too). All you need to is convert the lists to strings and back:
seqToFind = ['Rita','Sue','Bob']
seqToReplace = ['A','B','C']
#joiner should of course be a substring that doesn't occur in the list
joiner = "~~"
stringToFind = string.join(seqToFind,joiner)
stringToSearch = string.join(seqToSearch,joiner)
stringToReplaceWith = string.join(seqToReplace,joiner)
resultString = stringToSearch.replace(stringToFind,stringToReplaceWith)
resultSeq = resultString.split(joiner)
That last block could also be written as:
#s ends up with the resulting list
s = seqToSearch
But that's verging on the obfuscated :)
More information about the Python-list