-1

i just want to know how to turn a string expression into a normal expression, where I can solve it.

Example:

"1 + 1"

i don't want the above in a string, I want it to be

1 + 1

Another example:

"2(4 - 3) * 2"

i want to above to be the bottom instead:

2(4 - 3) * 2

like that. So could someone please let me know how to do that? Thanks!

please don't say use eval, since it solves the equation. I don't want to solve it, I want it to not be in a string.

Sovereign
  • 7
  • 2
  • 6
  • Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – zoldxk May 06 '21 at 01:08
  • don't mind about the `solve it` part. all I want to do is make the string expression to a normal expression which should **not be in a string**. – Sovereign May 06 '21 at 11:28
  • Nobody here seems to know what you mean when you say "a normal expression", me included. Perhaps you need to elaborate on that a bit. E.g. what do you intend to do with this "normal expression"? (meaning that printing it can be done when it is a string, solving/evaluating/executing it can be done with `eval`, there are some more esoteric use-cases, but I can't imagine that is what you're asking about since your question then would include words like syntax trees etc.) – thebjorn May 15 '21 at 17:52

4 Answers4

1

Use eval

>>>eval('1 + 1')
2
zoldxk
  • 2,632
  • 1
  • 7
  • 29
  • I'm not using `eval`, since that's **solves** it, all I want to do is turn the expression to a normal expression, not in a string. – Sovereign May 06 '21 at 11:25
1

You can use eval("1 + 1") to evaluate any string as a python expression.

"2(4 - 3) * 2" isn't a valid python expression, so you wouldn't be able to eval that.

You have to be careful when using eval though if you're passing in any user-provided input, as it effectively allows them to execute any arbitrary code string.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • i'm not trying to use `eval` or try to solve it. All I want is to remove it from a string and make it a normal expression. Not a expression in string. – Sovereign May 06 '21 at 11:24
1

Use eval(str):

>>> eval('2 * (4 - 3) * 2')
4

if you nead use for, def, import and other Use exec(str).

  • Executing your example gives an error. If the user doesn't know about the eval instruction, he would probably dont understand why tis fails either. You could give some hint about it. – Rodrigo Rodrigues May 06 '21 at 02:42
  • in math `2(4 - 3) * 2 = 4` but in python `SyntaxError` for py `2 * (4 - 3) * 2` is correct –  May 06 '21 at 07:04
  • No, i'm not trying to solve it, I'm trying to make that expression a normal expression, not in a string. – Sovereign May 06 '21 at 11:26
-1

Python provides a few ways of executing it's own code. There are usually two Built-in Functions that allow us to execute python code from within python -:

  • eval function -: The eval function can be used to execute any expression as incase is needed by you, but note that multiple lines worth of python code cannot be executed using eval.
  • exec function -: The exec function can be used to execute multiple lines of python code also dynamically. It thus is different from the eval function due to it's ability to be able to execute more than just a python expression.

Now for your use case since you just want to execute a python expression stored in a string lets say e the following can be done -:

e = '(2 *(4 - 3)) * 2' # Note that the previously written expression [2(4 - 3) * 2 is not a valid python expression as pointed out by @Brendan Abel]
result = eval(e) # The eval function executes the expression e and the result is stored in the result variable.

EDIT: So after your comment, your need seems to be to convert it into a normal expression that is at your disposal and can be run at any time.

For the same we can make a class called Expression, then we can make it store the expression as a .py file.

The expression object of the class can then be used to run it at anytime and also shall be disposed at the end to delete the .py file created initially.

The code for the same will look something like this -:

import importlib # Used for the Expression.run method.
import os # Used for the Expression.dispose method.

class Expression() :
    def __init__(self, expr_name, str_expr) :
        # This function is called at initialization of an Expression object.
        
        self.expr_name = expr_name
        self.str_expr = str_expr
        
        self.module_obj = None # To store the module object returned by the import_module function.(defaultly None)
        
        self.store() # Saves the expression as a .py file.
        return
    
    def store(self) :
        # Creates a .py file with the name as that of the expression name to store
        # the string expression for it to be later executed.
        
        addr = self.expr_name + '.py'
        with open(addr, 'w') as f :
            f.write(self.str_expr)
        return
    
    def dispose(self) :
        # Should be called either at the end of the program or whenever the use
        # for the expression has ended and no further use is needed, this function
        # deletes the .py file created initially to store the expression.
        
        addr = self.expr_name + '.py'
        os.remove(addr)
        return
    
    def run(self) :
        # This function can be called to execute the expression and it imports
        # the .py file previously created to indirectly execute it.
        
        if self.module_obj == None :
            # If the module_obj value is None it means the module is being
            # imported for the first time.
            self.module_obj = importlib.import_module(self.expr_name)
        else :
            # If the module_obj value is not None then the module has been
            # imported before and thus is now reloaded using the previously
            # stored module object.
            self.module_obj = importlib.reload(self.module_obj)
        return
    
    pass

# The string expression.
e = 'print((2 * (4 - 3)) * 2)'
# Creating an expression object.
e_ = Expression('e1', e)

# Will print the result three times
e_.run()
e_.run()
e_.run()

# Now we dispose the expression since it is not needed anymore.
e_.dispose()

The output of the same is -:

4
4
4

After complete execution of program, all the used .py expression files are deleted if the expressions used have been disposed.

typedecker
  • 1,351
  • 2
  • 13
  • 25
  • i'm not trying to use `eval` or `exec` to solve it. I just want to turn a string expression to a normal expression which is **not in a string.** – Sovereign May 06 '21 at 11:27
  • Well then you can use file i-o to write a file and write the expression to it and save it with .py extension. Then it turns into a normal python expression. – typedecker May 06 '21 at 11:51
  • Also its not very clear as to where exactly you want to place the normal expression. – typedecker May 06 '21 at 11:51
  • If in the same place as the string expression you can again write the whole current file code to a new .py file and replace the string expression for a normal one. – typedecker May 06 '21 at 11:52
  • i meant like this: i have a string expression. But I want to turn it into a normal expression, and when I run the normal expression, it shouldn't be in a string. – Sovereign May 06 '21 at 12:41
  • Yeah so if you save that string expression in a .py file it can be run! – typedecker May 07 '21 at 07:49
  • @Sovereign I have updated the solution please see to it and whether this satisfies your need, – typedecker May 07 '21 at 08:43
  • ok thanks for this, i have a few things though. 1. this seems like modules and files and all, could you make this simple? Without modules or files, and just with basic simple code? Also another thing is, my request was to convert the string expression to a normal expression, that is not in a string. Your code solves it. But you can still do my first request, since it may help. Also, this is unrelated but, do you know who closed my question? This question isn't a duplicate, if you know who did it, please let them know this isn't a duplicate, and they are misunderstanding it. – Sovereign May 07 '21 at 13:05
  • Just to let you know, you can still make the code simple. It may be what i want. You can fulfill my other requests too. Thanks! – Sovereign May 07 '21 at 13:05
  • @Sovereign I tried making the code as simple as possible and the only module imported that might be a little bit new to you is the importlib module, the os module is a very common module used by everyone. And where I did use the importlib module I mentioned what the function did the code is very simple if you know the basic concepts of python such as OOPS. – typedecker May 07 '21 at 14:44
  • @Sovereign The comments in my code themselves tell what each line of the code does, I can try to make it more easier but I am afraid it is not possible. Also I did not vote to close your question and do not know who did. But just to clarify a question is closed when more than one person may vote to close that question i.e. with a majority. Eventhough I also feel that closing a question just because someone cannot solve it is unfair, but again the rules here do not change as per the changing environment they remain constant. – typedecker May 07 '21 at 14:44
  • ok thank you for all this information. So for the code, yes I do know the modules, but nevermind that. So your code solves it, I just want to change the expression from a string to a normal expression without a string. Also if you have anymore examples of code other than the one you gave, please let me know. Thanks once again!! – Sovereign May 07 '21 at 17:45