# string to complex number in python by R4R Team

- complex() function take two argument normally which is real and imaginary number.
-But there are also possible to pass a string as argument in complex() function then what will happen

Syntax-

complex(string)

Example-

complex number is n=complex("3","2")
then it will give an error
but when
complex number is n=complex("3")
then it will give 3+0j

complex number is n=complex("1+2j")
then it will give 1+2j

program-

#pass numbers as argument in complex
n=complex(3,2)
print("Complex number is ",n)
print("real part is ",n.real)
print("Imaginary part is ",n.imag)

#pass string as argument
n=complex("3")
print("Complex number is ",n)
print("real part is ",n.real)
print("Imaginary part is",n.imag)

n=complex("3+4j")
print("Complex number is ",n)
print("real part is ",n.real)
print("Imaginary part is",n.imag)

output-

Complex number is (3+2j)
real part is 3.0
Imaginary part is 2.0
Complex number is (3+0j)
real part is 3.0
Imaginary part is 0.0
Complex number is (3+4j)
real part is 3.0
Imaginary part is 4.0

-In this program, we pass a string as a argument in complex() so it consider that numeric string is real part and imaginary part is 0.
-If we try to pass two string as argument then what will happen ?

program-

#pass two string as argument
n=complex("3","2")
print("Complex number is ",n)

output-

n=complex("3","2")
TypeError: complex() can't take second arg if first is a string

-If we try to put alphabatic string as a argument then what will happen ?

program-

#pass two string as argument
n=complex("a")
print("Complex number is ",n)

output-

n=complex("a")
ValueError:complex() arg is a malformed string