howto split string with both comma and semicolon delimiters

D

dmitrey

hi all,
howto split string with both comma and semicolon delimiters?

i.e. (for example) get ['a','b','c'] from string "a,b;c"

I have tried s.split(',;') but it don't work
Thx, D.
 
G

Gary Herron

dmitrey said:
hi all,
howto split string with both comma and semicolon delimiters?

i.e. (for example) get ['a','b','c'] from string "a,b;c"

I have tried s.split(',;') but it don't work
Thx, D.

The regular expression module has a split function that does what you
want.
>>> import re
>>> r =',|;' # or this also works: '[,;]'
>>> s = "a,b;c"
>>> re.split(r,s)
['a', 'b', 'c']


Gary Herron
 
D

Daniel Fetchinson

howto split string with both comma and semicolon delimiters?
i.e. (for example) get ['a','b','c'] from string "a,b;c"

I have tried s.split(',;') but it don't work

A very pedestrian solution would be:

def multisplit( s, seps ):

words = [ ]
word = ''
for char in s:
if char in seps:
if word:
words.append( word )
word = ''
else:
word += char

if word:
words.append( word )

return words


Cheers,
Daniel
 
B

bvdp

dmitrey said:
hi all,
howto split string with both comma and semicolon delimiters?

i.e. (for example) get ['a','b','c'] from string "a,b;c"

I have tried s.split(',;') but it don't work
Thx, D.

Howabout:

s = s.replace(";", ",")
s = s.split(",")
 
M

MRAB

dmitrey said:
hi all,
howto split string with both comma and semicolon delimiters?
i.e. (for example) get ['a','b','c'] from string "a,b;c"
I have tried s.split(',;') but it don't work
Thx, D.

Howabout:

s = s.replace(";", ",")
s = s.split(",")

I've wondered in the past whether there would be sufficient need for
things like s.split((',', ';')) and s.partition((',', ';')).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top