Reputation: 15
I have a string that looks like this
+0.6810+0.0266-0.0140-0.0111-0.0080-00.026-0.0229+000.84
I need to parse this string at each +/- sign and while at the same time keeping the signs with the numbers so that they can be stored into variables. So what I want to have come out are varialbes for each of seven positive or negative numbers like
a= 0.6810
b= 0.0266
c= -0.0140
etc
I am able to spit the string but now now a way converting to a flow and keeping the sign current code to split string is:
print (re.split(r'[+-]+',dataString))
Upvotes: 0
Views: 233
Reputation: 213351
You can use re.findall
on your string: -
>>> string = "+0.6810+0.0266-0.0140-0.0111-0.0080-00.026-0.0229+000.84"
>>>
>>> import re
>>> matches = re.findall(r'[-+]\d+\.\d+', string)
>>> matches
['+0.6810', '+0.0266', '-0.0140', '-0.0111', '-0.0080', '-00.026', '-0.0229',
'+000.84']
>>>
>>> a = float(matches[0])
>>> 0.681
>>> (a, b, c, d, e, f, g) = map(float, matches)[:7]
Upvotes: 2
Reputation: 1417
What about a string replace with a split? Something like
print (re.replace(r"([+-])", " \1", dataString)).split()
Might not be the best way, but it'll do the job...I think, didn't test it!
Upvotes: 0
Reputation: 101999
If the string is like the one you posted you can simply do something like:
your_string.replace('-', '+-').split('+')
But this is not robust.
Anyway you could simply use the re.findall
method. I think:
re.findall(r'[+-]\d+(\.\d+)?', your_string)
should do the trick.
Actually it would also match integers, if your numbers always have the period and digits on both sites you can use:
r'[+-]\d+\.\d+
Upvotes: 3