Write a functon to modify a certain string in a certain way by adding character

In [15]: def add_multiplies(input_string): 
    ...:     return re.sub(r'([^-+*/])\(', r'\1*(', input_string) 
    ...:      
    ...:      
    ...:                                                                                                                                    

In [16]: for example in examples: 
    ...:     print(f"{example} -> {add_multiplies(example)}") 
    ...:                                                                                                                                    
4(3) -> 4*(3)
(4)(3) -> (4)*(3)
4*2 + 9 -4(-3) -> 4*2 + 9 -4*(-3)
(-9)(-2) (4) -> (-9)*(-2) *(4)
4^(3) -> 4^*(3)
(4-3)(4+2) -> (4-3)*(4+2)
(Aflkdsjalkb)(g) -> (Aflkdsjalkb)*(g)
g(d)(f) -> g*(d)*(f)
(g)-(d) -> (g)-(d)

tl;dr Rather than thinking of this as string transformation, you might:

  1. Parse an input string into an abstract representation.

  2. Generate a new output string from the abstract representation.


Parse input to create an abstract syntax tree, then emit the new string.

Generally you should:

  1. Create a logical representation for the mathematical expressions.
    You'll want to build an abstract syntax tree (AST) to represent each expression. For example,

    2(3(4)+5)

    could be form a tree like:

      *
     /  \
    2    +
        /  \
       *    5
      /  \
     3    4
    

    , where each node in that tree (2, 3, 4, 5, both *'s, and the +) are each an object that has references to its child objects.

  2. Write the logic for parsing the input.
    Write a logic that can parse "2(3(4)+5)" into an abstract syntax tree that represents what it means.

  3. Write a logic to serialize the data.
    Now that you've got the data in conceptual form, you can write methods that convert it into a new, desired format.


Note: String transformations might be easier for quick scripting.

As other answers have shown, direct string transformations can be easier if all you need is a quick script, e.g. you have some text you just want to reformat real quick. For example, as @PaulWhipp's answer demonstrates, regular expressions can make such scripting really quick-and-easy.

That said, for professional projects, you'll generally want to parse data into an abstract representation before emitting a new representation. String-transform tricks don't generally scale well with complexity, and they can be both functionally limited and pretty error-prone outside of simple cases.


I'll share mine.

def insertAsteriks(string):

    lstring = list(string)
    c = False

    for i in range(1, len(lstring)):

        if c:
            c = False
            pass
        elif lstring[i] == '(' and (lstring[i - 1] == ')' or lstring[i - 1].isdigit() or lstring[i - 1].isalpha() or (lstring[i - 1] == ' ' and not lstring[i - 2] in "*^-+/")):
            lstring.insert(i, '*')
            c = True

    return ''.join(lstring)

Let's check against your inputs.

print(insertAsteriks("4(3)"))
print(insertAsteriks("(4)(3)"))
print(insertAsteriks("4*2 + 9 -4(-3)"))
print(insertAsteriks("(-9)(-2) (4)"))
print(insertAsteriks("(4)^(-3)"))
print(insertAsteriks("ABC(DEF)"))
print(insertAsteriks("g(d)(f)"))
print(insertAsteriks("(g)-(d)"))

The output is:

4*(3)
(4)*(3)
4*2 + 9 -4*(-3)
(-9)*(-2) (4)
(4)^(-3)
ABC*(DEF)
g*(d)*(f)
(g)-(d)

[Finished in 0.0s]

Tags:

Python

String