Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 781
Adeniregun Dipo Avatar asked Mar 08 '17 02:03

Adeniregun Dipo


People also ask

How do you convert to complex numbers in Python?

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

What does complex () do in Python?

Python complex() Function The complex() function returns a complex number by specifying a real number and an imaginary number.

How do you write imaginary i in Python?

In Python, the symbol j is used to denote the imaginary unit.

How do i convert a string to 3 in python?

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.


1 Answers

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.

like image 55
Francisco Avatar answered Sep 22 '22 23:09

Francisco