CKM
CKM

Reputation: 1971

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!

Upvotes: 2

Views: 1827

Answers (6)

Sandip
Sandip

Reputation: 9

   line.replace(' -1','').split(' ')
   # ['1','2','3','4'].

Upvotes: 0

Zach Ward
Zach Ward

Reputation: 127

I can't say whether this would be more efficient than some of the other solutions, but a list comprehension is very readable and could certainly do the trick:

line = '1 -1 2 3 -1 4'
t = [str(item) for item in line.split(" ") if int(item) >= 0]
>>> ['1', '2', '3', '4']

Upvotes: -1

MSeifert
MSeifert

Reputation: 152657

I'm not using a regex but a conditional list comprehension:

>>> line = '1 -1 2 3 -1 4'
>>> [substr for substr in line.split() if not substr.startswith('-')]
['1', '2', '3', '4']

Upvotes: 0

Sandipan Dey
Sandipan Dey

Reputation: 23101

You can try this too with lookahead:

print re.findall('(?<=[^-])\d+', ' ' +line)
# ['1', '2', '3', '4']

This is more generic since this will filter out all negative numbers.

line = '-10 12 -10 20 3 -2 40 -5 5 -1 1' 
print re.findall('(?<=[^-\d])\d+', ' ' +line)
# ['12', '20', '3', '40', '5', '1']

Upvotes: 0

DYZ
DYZ

Reputation: 57033

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()

Upvotes: 4

Amorpheuses
Amorpheuses

Reputation: 1423

Try:

t=re.split("\s+",line.replace("-1"," "))

Upvotes: 1

Related Questions