我有這個字串:
"487351.25373014854 - 152956.2387091797 P_1(x)
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x)
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x)
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x)
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x)
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x)
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x)
5.362954837187194e-23 P_14(x)"
我正在嘗試全部替換P_n(x)為*(x**n).
例如:
"1 - 2 P_1(x) 3 P_2(x) - 708.4250106547449 P_3(x)"
會回傳:
"1 - 2*(x**1) 3*(x**2) - 708.4250106547449*(x**3)"
uj5u.com熱心網友回復:
您可以使用re.sub()替換所有出現的該模式。
import re
s = "1 - 2 P_1(x) 3 P_2(x) - 708.4250106547449 P_3(x)"
pattern = r' P_(\d )\(x\)' # (\d ) captures the n in P_n
replace = r' * (x**\1)' # \1 uses the last captured n as a replacement
s_2 = re.sub(pattern, replace, s)
print(s_2)
輸出:
1 - 2 * (x**1) 3 * (x**2) - 708.4250106547449 * (x**3)
并提供您的完整輸入:
s_3 = """487351.25373014854 - 152956.2387091797 P_1(x)
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x)
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x)
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x)
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x)
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x)
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x)
5.362954837187194e-23 P_14(x)
"""
s_4 = re.sub(pattern, replace, s_3)
print(s_4)
輸出:
487351.25373014854 - 152956.2387091797 * (x**1)
14288.881396831219 * (x**2) - 708.4250106547449 * (x**3)
22.029508388530736 * (x**4) - 0.46451906903633394 * (x**5)
0.006931166409021728 * (x**6) - 7.493824771409185e-05 * (x**7)
5.934862864562062e-07 * (x**8) - 3.442722590115344e-09 * (x**9)
1.4457000568406937e-11 * (x**10) - 4.276159814629395e-14 * (x**11)
8.446505496408776e-17 * (x**12) - 9.998295324026605e-20 * (x**13)
5.362954837187194e-23 * (x**14)
uj5u.com熱心網友回復:
我會建議一個帶有replace()函式的簡單 for 回圈
for i in range(n):
mystr = mystr.replace('P_' str(i) '(x)', '*(x**' str(i) '2)')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396860.html
