converting a string to complex number python

Adeniregun Dipo picture Adeniregun Dipo · Mar 8, 2017 · Viewed 11.5k times · Source

im trying to convert inputted string to a float but when i do it i keep getting some kind of error so below is a sample of what i did. im pretty sure i did nothing wrong but if you spot any mistakes

     >>> a = "3 + 3j"
     >>> b=complex(a)
    >>> 
    ValueError: complex() arg is a malformed string
    >>> Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
     c= complex("3 + 3j")
    >>> 
    ValueError: complex() arg is a malformed string
    >>> Traceback (most recent call last):
    File "<stdin>", line 1, in <module>

P.S that is not the actual code im trying to write just a sample

Answer

Francisco C picture Francisco C · Mar 8, 2017

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.