Re: s.split() on multiple separators
- From: Bryan Olson <fakeaddress@xxxxxxxxxxx>
- Date: Sun, 30 Sep 2007 10:49:23 -0700
mrkafk@xxxxxxxxx wrote:
Hello everyone,
OK, so I want to split a string c into words using several different
separators from a list (dels).
I can do this the following C-like way:
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)).
Python 2.3 and up offers: for (i, word) in enumerate(c):
cp.extend(c[i].split(j))
c=cp
c
['ab', 'd', '', 'ab', '', '']
The bug lost some words, such as 'fdsa'.
But. Surely there is a more Pythonic way to do this?
When string.split() doesn't quite cut it, try re.split(), or
maybe re.findall(). Is one of these what you want?
import re
c = ' abcde abc cba fdsa bcd '
print re.split('[ce ]', c)
print re.split('[ce ]+', c)
print re.findall('[^ce ]+', c)
--
--Bryan
.
- Follow-Ups:
- Re: s.split() on multiple separators
- From: mrkafk
- Re: s.split() on multiple separators
- References:
- s.split() on multiple separators
- From: mrkafk
- s.split() on multiple separators
- Prev by Date: Re: Can you please give me some advice?
- Next by Date: code for number guessing by computer
- Previous by thread: Re: s.split() on multiple separators
- Next by thread: Re: s.split() on multiple separators
- Index(es):