How to convert a string to a complex number in Python?

15,212

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

Solution 2

Following the answer from Francisco Couzo, 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

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

>>> complex(''.join(a.split()))  # Remove all whitespace first
(3+3j)
Share:
15,212
Admin
Author by

Admin

Updated on July 27, 2022

Comments

  • Admin
    Admin almost 2 years

    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
    
  • Tyberius
    Tyberius about 2 years
    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.