How to convert a string to a complex number in Python?
Asked Answered
S

5

9

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
Shelashelagh answered 8/3, 2017 at 2:11 Comment(1)
Should be: a="3+3j".Quasimodo
I
15

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, but complex('1 + 2j') raises ValueError.

Ingle answered 8/3, 2017 at 2:14 Comment(0)
V
9

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)
Volcano answered 8/3, 2017 at 2:23 Comment(0)
K
6

complex's constructor rejects embedded whitespace. Remove it, and it will work just fine:

>>> complex(''.join(a.split()))  # Remove all whitespace first
(3+3j)
Kristalkristan answered 8/3, 2017 at 2:16 Comment(0)
A
0

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.

Avidin answered 15/6, 2021 at 19:52 Comment(1)
Eval you have to careful once you move to the case of parsing text from user input or a file rather than just entering your own complex number as a string.Monastery
B
0

With a dataframe x_df filled with strings that need to be converted. This solution worked for me. It's an asinine workaround, but it works.

vfunc = np.vectorize(eval)
x_full = vfunc(x_df.to_numpy())
Burnet answered 14/9, 2022 at 15:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.