Aman Kumar
Aman Kumar

Reputation: 27

remove from end of the string and add new char to he beginning?

I want to convert "23!-32/2!*3!-20" to "factorial(23)-32/factorial(2)*factorial(3)-20"
I could do this much:

import re
from math import factorial
operators = "\+\-\*\/"
exp = "23!-32/2!\*3!-20"

def splitter(stri):
    list1 = []
    for i in stri:
        list1.append(i)
    return list1

list2 = []
for i in re.findall("[\w\+\-\*\/][0-9]+?[!]",exp):
    i = re.sub("!", "",i)
    if i[0] in operators:
        i = splitter(i)
        i.insert(1,"factorial(")
        i.append(")")
        i = "".join(i)
    else:
        i = "factorial(" + i + ")"
    list2.append(i)

exp = "".join(list2)
print(exp)

the code does "seems" to work but then it only returns factorial(23)-32/factorial(2)*factorial(3) and eats away "-20" and "-32" from the string

Upvotes: 1

Views: 51

Answers (1)

Jan
Jan

Reputation: 43179

Regular expressions to the rescue:

import re

data = "23!-32/2!*3!-20"

result = re.sub(r'(\d+)!', r"factorial(\1)", data)
print(result)

Which yields

factorial(23)-32/factorial(2)*factorial(3)-20

Upvotes: 3

Related Questions