chandresh chandresh - 4 years ago 159
Python Question

Split python string with multiple delimiter

I want to split a python string

line = '1 -1 2 3 -1 4'
so that my output is a python list
['1','2','3','4']
. I tried solution given here and here. However, some strange output is coming. My code:

line = '1 -1 2 3 -1 4'
import re
t=re.split("-1| ", line)


output:

['1', '', '', '2', '3', '', '', '4']


Any help is appreciated!

DYZ DYZ
Answer Source

That was a tricky one :)

re.split(r"(?:\s-1)?\s",line)
#['1', '2', '3', '4']

And the fastest solution (runs about 4.5 times faster than the regex):

line.replace("-1 ", "").split()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download