I want to extract numbers from a string and store them in different variables.
for eg:- "92+23i"
is a complex number. I want to store 92 in variable num_real
and 23 in num_imagin
.
Python has predefined type as complex
however it expects the string to be of type "a+bj"
(note the j
instead of i
, and it should be without space). In your case you may replace "i"
with "j"
in your string and get your desired values as:
>>> my_str = "92+23i"
>>> my_num = complex(my_str.replace('i', 'j'))
From this complex number, you need to extract the desired values using my_num.imag
for imaginary part and my_num.real
for the real part of the complex number. For example:
>>> my_num.imag
23.0
>>> my_num.real
92.0
Your string is very close to parsing as a Python literal:
>>> s = '92+23i'
>>> import ast
>>> ast.literal_eval(s.replace('i', 'j'))
(92+23j)
Access the real and imaginary parts with num.real
and num.imag
.