Home > Blockchain >  How to replace brackets by using regex
How to replace brackets by using regex

Time:04-11

I have written a calculator for solving quadratic equations, using cmath.

So far I've successfully replaced 'j' into 'i' in the results, but failed to find a way to replace the brackets and the "0i" (if exist).

import cmath
a_2 = float(input('a: '))
b_1 = float(input('b: '))
c_0 = float(input('c: '))
delta = (b_1**2) - (4*a_2*c_0)
sol1 = (-b_1-cmath.sqrt(delta))/(2*a_2)
sol2 = (-b_1 cmath.sqrt(delta))/(2*a_2)
sol1i = re.sub(r'j', 'i', str(sol1))
sol2i = re.sub(r'j', 'i', str(sol2))
print(f'x_1={sol1i},x_2={sol2i}')

Result:

a: 1
b: 2
c: 1
x_1=(-1 0i),x_2=(-1 0i)

What I want:

a: 1
b: 2
c: 1
x_1=-1,x_2=-1

CodePudding user response:

Take a look at str.replace() or str.strip(). It will be much simpler and intuitive than using regex. (Same thing applies to your replacing j with i)

>>> sol1i.strip(")(")
'-1 0i'
>>> # or this option
>>> sol1i.replace(")", "").replace("(", "")
'-1 0i

UPD: even simpler it would be like this

>>> f"x_1={sol1.real:g}   {sol1.imag:g}i,x_2={sol2.real:g}   {sol2.imag:g}i"
x_1=-1   0i,x_2=-1   0i

UPD2: now I've noticed the option of omitting zero imaginary unit in print.

sol1 = (-b_1-cmath.sqrt(delta))/(2*a_2)
sol2 = (-b_1 cmath.sqrt(delta))/(2*a_2)
print(f"x_1={sol1.real:g}"   (f"   {sol1.imag:g}i" if sol1.imag else ""), end=",")
print(f"x_2={sol2.real:g}"   (f"   {sol2.imag:g}i" if sol2.imag else ""))
  • Related