Reputation: 1971
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
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
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
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
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