I would like to remove all non-numeric characters from a string, except operators such as +,-,*,/, and then later evaluate it. For example, suppose the input is 'What is 2+2?' The result should be '2+2' - keeping only the operator symbols and numeric digits.
How can I do this in Python? I tried this so far, but can it be improved?
def evaluate(splitted_cm):
try:
splitted_cm = splitted_cm.replace('x', '*').replace('?', '')
digs = [x.isdigit() for x in splitted_cm]
t = [i for i, x in enumerate(digs) if x]
answer = eval(splitted_cm[t[0]:t[-1] + 1])
return str(answer)
except Exception as err:
print(err)
expression = ''.join([x for x in splitted_cm if x.isdigit() or x in '+=/*'])eval()for anything that could possibly receive input from outside the program in any form. It is a critical security risk that allows the creator of that input to execute arbitrary code on your computer.4 cats + 3 dogs? What does happen?2+2. Your edit makes it people think, I want the output just like after removing all letters and other chars except numbers and operators.- Also: what should happen for an input like 4 cats + 3 dogs?My current environment does not need such an expression. No args given will be like4 cats + 3 dogs. The thing I'm working on will only give strings such as"what is 2+2?","what is 3+3". Just like those.