如何使用正则表达式替换括号
How to replace brackets by using regex
我用 cmath 写了一个求解二次方程的计算器。
到目前为止,我已成功将结果中的 'j' 替换为 'i',但未能找到替换方括号和“0i”(如果存在)的方法。
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}')
结果:
a: 1
b: 2
c: 1
x_1=(-1+0i),x_2=(-1+0i)
我想要的:
a: 1
b: 2
c: 1
x_1=-1,x_2=-1
看看 str.replace()
或 str.strip()
。它将比使用正则表达式更简单和直观。 (这同样适用于将 j
替换为 i
)
>>> sol1i.strip(")(")
'-1+0i'
>>> # or this option
>>> sol1i.replace(")", "").replace("(", "")
'-1+0i
UPD:更简单的是这样
>>> 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:现在我注意到在打印中省略零虚数单位的选项。
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 ""))
我用 cmath 写了一个求解二次方程的计算器。
到目前为止,我已成功将结果中的 'j' 替换为 'i',但未能找到替换方括号和“0i”(如果存在)的方法。
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}')
结果:
a: 1
b: 2
c: 1
x_1=(-1+0i),x_2=(-1+0i)
我想要的:
a: 1
b: 2
c: 1
x_1=-1,x_2=-1
看看 str.replace()
或 str.strip()
。它将比使用正则表达式更简单和直观。 (这同样适用于将 j
替换为 i
)
>>> sol1i.strip(")(")
'-1+0i'
>>> # or this option
>>> sol1i.replace(")", "").replace("(", "")
'-1+0i
UPD:更简单的是这样
>>> 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:现在我注意到在打印中省略零虚数单位的选项。
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 ""))