s.split() on multiple separators
Paul Hankin
paul.hankin at gmail.com
Sun Sep 30 19:07:36 EDT 2007
On Sep 30, 8:16 pm, mrk... at gmail.com wrote:
> > > c=' abcde abc cba fdsa bcd '.split()
> > > dels='ce '
> > > for j in dels:
> > > cp=[]
> > > for i in xrange(0,len(c)-1):
>
> > The "-1" looks like a bug; remember in Python 'stop' bounds
> > are exclusive. The indexes of c are simply xrange(len(c)).
>
> Yep. Just found it out, though this seems a bit counterintuitive to
> me, even if it makes for more elegant code: I forgot about the high
> stop bound.
You made a common mistake of using a loop index instead of iterating
directly.
Instead of:
for i in xrange(len(c)):
cp.extend(c[i].split(j))
Just write:
for words in c:
cp.extend(words.split(j))
Then you won't make a bounds mistake, and this snippet becomes a LOT
more readable.
(Of course, you're better using re.split instead here, but the
principle is good).
--
Paul Hankin
More information about the Python-list
mailing list