Probem:
I have a string containing different numbers, math signs and words, e.g.
str = ".1**2 + x/(10.0 - 2.E-4)*n_elts"
I would like to extract all numbers and keep the parts between the numbers so I can place it together again later (after working on the numbers).
lst = [".1", "**", "2", " + ", "x/(", "10.0", " - ", "2.E-4", ")*n_elts"]
would be one of many acceptable results. The elements which are not numbers can be split up further in any arbitrary way, since the next step will be
"".join(process(l) for l in lst)
where process could look like this
(suggestions for a better way to check l
is a number welcome):
def process(l):
try:
n = float(l)
except ValueError:
return l
else:
return work_on_it(l)
Current state:
From this answer I figured out how to keep the deliminators and worked my way to
lst = re.split('( |\+|\-|\*|/)', ".1**2 + x/(10.0 - 2.E-4)*n_elts")
Now I need to somehow avoid splitting the 2.E-4
.
I tried to work out a regex (vi syntax, hope this is universal) that covers all numbers that could possibly appear and think
\d*\.\d*[E|e]*[|+|-]*\d*
should be ok.
One strategy would be to somehow get this into re
.
I also found a related answer that seems to do the number matching part. It might be a bit more complex than I need, but mainly I do not know how to combine it with the keeping deliminators bit.