2

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!

6 Answers 6

4

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()
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

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

3 Comments

I had that sol is mind. How about time complexity of the above code or Can we do that without replacing -1 by space?
Yes I would imagine it's not the most efficient of possible solutions. Would have to do some timing tests.
The replace with space appears to be consistently faster by 3-4 times - but the reader should probably do his/her own timing tests to confirm.
0

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']

Comments

0

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']

Comments

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

Comments

-1

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']

1 Comment

What about 0's?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.