Adeniregun Dipo
Adeniregun Dipo

Reputation: 125

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

Upvotes: 9

Views: 25033

Answers (5)

user2983936
user2983936

Reputation: 43

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())

Upvotes: 0

Dani Medina
Dani Medina

Reputation: 909

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)

Upvotes: 9

sonnehansen
sonnehansen

Reputation: 130

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.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155477

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

>>> complex(''.join(a.split()))  # Remove all whitespace first
(3+3j)

Upvotes: 6

Francisco
Francisco

Reputation: 11496

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.

Upvotes: 15

Related Questions