Home > Mobile >  Replace all occurrences in a string by another string
Replace all occurrences in a string by another string

Time:12-29

I have this string:

"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)"

I'm trying to replace all P_n(x) by *(x**n).

For example:

"1 - 2 P_1(x)   3 P_2(x) - 708.4250106547449 P_3(x)"

would return:

"1 - 2*(x**1)   3*(x**2) - 708.4250106547449*(x**3)"

CodePudding user response:

You can use re.sub() to replace all occurrences of that pattern.

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)

Output:

1 - 2 * (x**1)   3 * (x**2) - 708.4250106547449 * (x**3)

And with your full input:

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)

Output:

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)

CodePudding user response:

I would suggest a simple for loop with the replace() function

for i in range(n):
    mystr = mystr.replace('P_' str(i) '(x)', '*(x**' str(i) '2)')
  • Related