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
Converting real numbers to complex number An complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and imaginary part can be represented by imag().
Python complex() Function The complex() function returns a complex number by specifying a real number and an imaginary number.
In Python, the symbol j is used to denote the imaginary unit.
We can convert numbers to strings using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.
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, butcomplex('1 + 2j')
raisesValueError
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With