'How to convert a string to a complex number in Python?
I'm trying to convert an input string to a float but when I do it I keep getting some kind of error, as shown in the sample below.
>>> a = "3 + 3j"
>>> b = complex(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
Solution 1:[1]
From the documentation:
Note
When converting from a string, the string must not contain whitespace around the central + or - operator. For example,
complex('1+2j')is fine, butcomplex('1 + 2j')raisesValueError.
Solution 2:[2]
Following the answer from Francisco, the documentation states that
When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.
Remove all the spaces from the string and you'll get it done, this code works for me:
a = "3 + 3j"
a = a.replace(" ", "") # will do nothing if unneeded
b = complex(a)
Solution 3:[3]
complex's constructor rejects embedded whitespace. Remove it, and it will work just fine:
>>> complex(''.join(a.split())) # Remove all whitespace first
(3+3j)
Solution 4:[4]
Seems that eval works like a charm. Accepts spaces (or not) and can multiply etc:
>>> eval("2 * 0.033e-3 + 1j * 0.12e-3")
(6.6e-05+0.00012j)
>>> type(eval("2 * 0.033e-3+1j*0.12 * 1e-3"))
<class 'complex'>
There could be caveats that I am unaware of but it works for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Francisco |
| Solution 2 | Francisco |
| Solution 3 | ShadowRanger |
| Solution 4 | sonnehansen |
