1

I am using python which I am pretty new to and could do with some guidance with what I believe to be a string formatting problem.

I have an output from an external program that I want to "translate" into floats. The output contains two numbers that may or may not be in scientific notation and can have up to 15 digits after the decimal point (which I have omitted here).

(-1.040e-05+3.1676e-03j) I want this to become two separate numbers like this -0.00001040 , 0.0031676

other examples of the output data in its currently useless form are as follows (0.0572636-0.419420j) would become 0.0572636 , -0.419420 (0.000194+4.85091e-05j)

I aim to take the two numbers contained in each pair of brackets, square them and add them together. If the result is two number in scientific notation then that is fine, so long as I am able to perform math operations on them. Also the minus sign doesn't need to survive the transformation as that would disappear when I square it anyway. If that makes things easier.

The approach I am currently taking is a rather convoluted and messy method. Using x.find to locate the 'e', '-' and '+' and then interpreting which parts of the string should be extracted to form the number.

I am also unfamiliar with the re module and unsure how to use it to extract the right format.

Any help would be apprieciated

1
  • Please add your code. Commented Jul 15, 2013 at 15:56

2 Answers 2

3

You can parse complex numbers in Python like this:

>>> c=complex('-1.040e-05+3.1676e-03j')
>>> c.real
-1.04e-05
>>> c.imag
0.0031676
>>>

It works with float and integer numbers, too:

>>> f=complex('100.01')
>>> f.real
100.01
>>> f.imag
0.0
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

@CalumHill I'm glad I could help. Can you please mark the answer as correct if you are happy with it?
Oh, I just noticed that you marked the other answer - that's OK.
1

You can also use the excellent numpy package:

import numpy as np
i = np.array(-1.040e-05+3.1676e-03j)
i.real

>> array(-1.04e-05)

i.imag

>> array(0.0031676)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.