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
1
  • Should be: a="3+3j". Commented Mar 8, 2017 at 2:16

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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)

Comments

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.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.