0

I have complex number in the form of a string

x = 1+3j

Using the split() method of strings , I want to break it into the real and imaginary parts.

What I tried : I used the + as a separator of the string and got the real and imaginary values.

Problem: The complex number can also be3-7j , I that case , split() fails as the string does not have a +.

What a want is that the split() should split the string when it encounters either + or -

  • Does this answer your question? [Split string with multiple delimiters in Python](https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python) – RvdK Oct 20 '20 at 08:19
  • @RvdK , I saw it , But in my case I have to ignore the `+` and `-` if it occurs in the beginning or the end. Example `-3+5j` –  Oct 20 '20 at 08:22
  • How could `+` and `-` occur at the end? – GZ0 Oct 20 '20 at 08:25
  • @GZ0 , In the example , `x = -3+5j` if I use `re.split('-|+' , x)` (as mentioned in the link by @RvdK), then the split would be ['3', '5j'] . That is , the real part lost its `-` sign which I dont want –  Oct 20 '20 at 08:29
  • @NeoNØVÅ7 That is an occurence at the beginning, not the end. You comment says "in the beginning or the end". So I was wondering what that refers to. – GZ0 Oct 20 '20 at 08:30
  • @GZ0 ooops . Ignore that, I cant edit it now since I already commented after that –  Oct 20 '20 at 08:31
  • @NeoNØVÅ7 Is `3+-2j` a valid input? – GZ0 Oct 20 '20 at 08:34
  • @GZ0 , Ya it could be . but for the time being , your comment on x.real an x.imag does the job. –  Oct 20 '20 at 08:35

1 Answers1

0

you can try this :

import numpy as np
y=complex(x)
xr,xi=np.real(y),np.imag(y)

I don't know if you want to keep them as strings, but if you do, just add str() around np.real(y) and np.imag(y).

Note that it doesn't work with you have spaces within your string.

NHL
  • 277
  • 1
  • 6