-1

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
WildFire
  • 79
  • 1
  • 9

2 Answers2

2

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • That was just an example , i mean '23x + 23y = 0' and extract the numbers only . – WildFire Mar 29 '18 at 06:05
  • @WILDFIRE Your question was unclear then. For this, you might need to take a look at: [*Python: Extract numbers from a string*](https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string) – Moinuddin Quadri Mar 29 '18 at 06:20
  • those answer are beyond my understandings. – WildFire Mar 29 '18 at 10:44
1

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.

wim
  • 338,267
  • 99
  • 616
  • 750