So, I have a line that looks, for example, like "012 + 2 - 01 + 24"
. I want to be able to quickly (less code) evaluate this expression ...
I could use eval () in a string, but I don't want 012
represented in octal (10), I want it to be represented as int (12).
My solution for this works, but it is not elegant. I seem to suggest that there is a really good pythonic way to do this.
My decision:
#expression is some string that looks like "012 + 2 - 01 + 24" atomlist = [] for atom in expression.split(): if "+" not in atom and "-" not in atom: atomlist.append(int(atom)) else: atomlist.append(atom)
Basically, I spoil, add a string and find numbers in it and turn them into ints, and then I rebuild the string with ints (essentially removing the leading 0, except where 0 is a number on its own).
How can this be done better?
source share