Search code examples
pythonstringtype-conversioncomplex-numbersstring-conversion

Python: convert string-pair to complex number


Here is my complex number. *I retrieved it out of a file:

re, im = line[11:13]
print(re) # -4.04780617E-02
print(im) # +4.09889424E-02

At the moment, it is just a pair of strings. How can I combine these into a complex number?

I've tried five times:

z = complex(re, im)
# ^ TypeError: complex() can't take second arg if first is a string

z = complex(float(re), float(im))
# ^ ValueError: could not convert string to float: re(tot)

z = float(re) + float(im) * 1j
# ^ ValueError: could not convert string to float: re(tot)

z = complex("(" + re + im + "j)")
# ValueError: complex() arg is a malformed string

z_str = "(%s%si)" % (re, im) # (-4.04780617E-02+4.09889424E-02i)
z = complex(z_str)
# ValueError: complex() arg is a malformed string

Solution

  • z = complex(float(re), float(im))