How to convert engineering notation of numbers to scientific in equation using python

StackOverflow https://stackoverflow.com/questions/13722658

  •  04-12-2021
  •  | 
  •  

Domanda

I have equation strings where all numbest in engineering notation like:

"(10u*myvar1)+(2.5f*myvar2)/myvar3"

I need to convert all numbers in this equation strings to scientific notation so that result will be like like:

"(10e-6*myvar1)+(2.5e-15*myvar2)/myvar3"

Do anyone have idea how to make this simple?

The hard way I think to split this with re.findall to numbers and other things, than fix numbers and rejoin to string. Like:

vals=re.findall('[\d.\w]+',param_value) #all numbers
operators=re.findall('[^\d.\w]+',param_value) #all not numbers

And than work on this two lists. But it seems too complicated. I don't see simple way to join this two lists back to string.

È stato utile?

Soluzione

You can do a simple regex substitution:

>>> units = 'munpf'
>>> def f(match):
    num = match.group(0)
    exp = -3 * (units.index(num[-1]) + 1)
    return num[:-1] + '10e' + str(exp)

>>> expr = "(10u*myvar1)+(2.5f*myvar2)/myvar3"

>>> re.sub(r'\b\d+(\.\d*)?' + '[%s]' % units + r'\b', f, expr)
'(10e-6*myvar1)+(2.5e-15*myvar2)/myvar3'

It's easy to extend if you want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top