473,326 Members | 2,438 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

How do I convert arithemtic string (like "2+2") to a number?

Hello, I need to convert a string to a number, but the string can
contain +,-,* and / as well as parenthesis. For example, if I have the
string "30/(6+9)" I would like a function that returned the number 2.

I actually wrote a java function that did this a couple of years ago, in
school, as an excersise in "binary trees". I lost it, and most of my
programming knowledge, but I figured perhaps there is a way to do this
easily in python? It seems to me like it could be a common problem.

/Arvid Andersson
Jul 18 '05 #1
8 2314
Use the eval function:
eval("30/(6+9)")

2

Michael

Jul 18 '05 #2
On Sat, Feb 05, 2005 at 02:11:07PM -0800, Michael Hartl wrote:
Use the eval function:
eval("30/(6+9)")

2


Thanks, just what I was looking for!

Jul 18 '05 #3
On Sat, 2005-02-05 at 17:11, Michael Hartl wrote:
Use the eval function:
eval("30/(6+9)")

2

Michael


Sure, if you trust the source of the string you are evaluating. If this
is a form submission on your web site, be wary of the nefarious user who
might submit to you:

commands.getoutput( "rm -rf %(HOME)s"%os.environ )

as the "expression" to evaluate.
Adam DePrince
Jul 18 '05 #4
Adam brings up a good point: eval is a very general function which
evaluates an arbitrary Python expression. As a result, it (and its
close cousin exec) should be used with caution if security is an issue.

Michael

Jul 18 '05 #5
Michael Hartl wrote:
Adam brings up a good point: eval is a very general function which
evaluates an arbitrary Python expression. As a result, it (and its
close cousin exec) should be used with caution if security is an issue.


To get a secure eval for simple mathematical expressions, it should
suffice to check the string in the following way:

It does not contain characters other than operators, numbers, dots and
parentheses (perhaps you want to allow 'e' for floats, but you should
make sure that the 'e' is surrounded by numbers or optionally followed
by a +/- sign).

If you want to go a step further, you could parse the string to eval
with the parser/tokenize/... modules and verify the parse tree that it
contains nothing except operators and numbers.

Reinhold
Jul 18 '05 #6
Well, a bit more secure would be

eval(expression, {'__builtins__': {}}, {})

or alike.

Jul 18 '05 #7
"Adomas" <ad******************@gmail.com> writes:
Well, a bit more secure would be

eval(expression, {'__builtins__': {}}, {})

or alike.


Don't believe this without (or even with ;-) very careful thought,
anyone. Google for rexec.
John
Jul 18 '05 #8
John J. Lee wrote:
"Adomas" <ad******************@gmail.com> writes:

Well, a bit more secure would be

eval(expression, {'__builtins__': {}}, {})

or alike.

Don't believe this without (or even with ;-) very careful thought,
anyone. Google for rexec.
John

This module provides a more systematic way to set up restricted evaluation:
"""Restricted evaluation

Main entry point: r_eval()
For usage see class tests or run them using testall()"""
import types
import compiler
import operator

import sys, os # used only for testing

ast = compiler.ast

class Eval_Error(Exception):
def __init__(self,error,descr = None,node = None):
self.error = error
self.descr = descr

def __repr__(self):
return "%s: %s" % (self.error, self.descr)
__str__ = __repr__
class AbstractVisitor(object):
"""Standard depth-first AST walker - dispatches to methods
based on Node class name"""
def __init__(self):
self._cache = {} # dispatch table

def visit(self, node,**kw):
if node is None: return None
cls = node.__class__
meth = self._cache.setdefault(cls,
getattr(self,'visit'+cls.__name__,self.default))
return meth(node, **kw)

def default(self, node, **kw):
for child in node.getChildNodes():
return self.visit(child, **kw)
visitExpression = default

class Eval(AbstractVisitor):
"""An AST walker that implements a replacement to built-in eval.

See r_eval for entry point/usage.

Provides hooks for managing name resolution, proxying objects,
and controlling attribute access

Does not implement:
List Comprehensions, Generator Expressions, Lambda
Ellipsis (can this be used without numpy?)
"""
def __init__(self, context = globals()):
super(Eval,self).__init__()
self.context = context

# Namespace interface. Safe implementations should override these methods
# to implement restricted evaluation. This implementation simply
# evals the name in self.context and provides no proxying or
# attribute lookup restrictions

def lookup(self, objname):
"""Called only by visitName. Raise an exception here
to prevent any direct name resolution, but note that
objects may be returned by callables or attribute lookups"""
return eval(objname, self.context)

def getObject(self, obj):
"""Called by all name resolvers and by CallFunc. Provides
a hook for proxying unsafe objects"""
return obj

def getAttribute(self,obj,attrname):
"""Called by visitGetattr"""
return getattr(obj,attrname)

# End Namespace interface
# Syntax nodes follow by topic group. Delete methods to disallow
# certain syntax.

# Object constructor nodes
def visitConst(self, node, **kw):
return node.value
def visitDict(self,node,**kw):
return dict([(self.visit(k),self.visit(v)) for k,v in node.items])
def visitTuple(self,node, **kw):
return tuple(self.visit(i) for i in node.nodes)
def visitList(self,node, **kw):
return [self.visit(i) for i in node.nodes]
def visitSliceobj(self,node,**kw):
return slice(*[self.visit(i) for i in node.nodes])
def visitEllipsis(self,node,**kw):
raise NotImplementedError, "Ellipsis"

# Binary Ops
def visitAdd(self,node,**kw):
return self.visit(node.left) + self.visit(node.right)
def visitDiv(self,node,**kw):
return self.visit(node.left) / self.visit(node.right)
def visitFloorDiv(self,node,**kw):
return self.visit(node.left) // self.visit(node.right)
def visitLeftShift(self,node,**kw):
return self.visit(node.left) << self.visit(node.right)
def visitMod(self,node,**kw):
return self.visit(node.left) % self.visit(node.right)
def visitMul(self,node,**kw):
return self.visit(node.left) * self.visit(node.right)
def visitPower(self,node,**kw):
return self.visit(node.left) ** self.visit(node.right)
def visitRightShift(self,node,**kw):
return self.visit(node.left) >> self.visit(node.right)
def visitSub(self,node,**kw):
return self.visit(node.left) - self.visit(node.right)

# Unary ops
def visitNot(self,node,*kw):
return not self.visit(node.expr)
def visitUnarySub(self,node,*kw):
return -self.visit(node.expr)
def visitInvert(self,node,*kw):
return ~self.visit(node.expr)
def visitUnaryAdd(self,node,*kw):
return +self.visit(node.expr)

# Logical Ops
def visitAnd(self,node,**kw):
return reduce(lambda a,b: a and b,[self.visit(arg) for arg in node.nodes])
def visitBitand(self,node,**kw):
return reduce(lambda a,b: a & b,[self.visit(arg) for arg in node.nodes])
def visitBitor(self,node,**kw):
return reduce(lambda a,b: a | b,[self.visit(arg) for arg in node.nodes])
def visitBitxor(self,node,**kw):
return reduce(lambda a,b: a ^ b,[self.visit(arg) for arg in node.nodes])
def visitCompare(self,node,**kw):
comparisons = {
"<": operator.lt, # strictly less than
"<=": operator.le,# less than or equal
">": operator.gt, # strictly greater than
">=": operator.ge, # greater than or equal
"==": operator.eq, # equal
"!=": operator.ne, # not equal
"<>": operator.ne, # not equal
"is": operator.is_, # object identity
"is not": operator.is_not # negated object identity
}
obj = self.visit(node.expr)
for op, compnode in node.ops:
compobj = self.visit(compnode)
if not comparisons[op](obj, compobj):
return False
obj = compobj
return True
def visitOr(self,node,**kw):
return reduce(lambda a,b: a or b,[self.visit(arg) for arg in node.nodes])
# Name resolution
def visitGetattr(self,node,**kw):
obj = self.visit(node.expr)
return self.getAttribute(obj,node.attrname)

def visitName(self,node, **kw):
return self.lookup(node.name)

def visitSlice(self,node,**kw):
obj = self.visit(node.expr)
objslice = obj[self.visit(node.lower):self.visit(node.upper)]
return self.getObject(objslice)

def visitSubscript(self,node,**kw):
obj = self.visit(node.expr)
subs = node.subs
if len(subs) > 1:
raise NotImplementedError, "Subscript must be integer or slice"
assert node.flags == "OP_APPLY"
return self.getObject(operator.getitem(obj,self.visit(sub s[0])))
# Callables
def visitCallFunc(self,node,**kw):
func = self.visit(node.node)

args = node.args
kwargs = self.visit(node.dstar_args) or {}
posargs = []
for arg in node.args:
if isinstance(arg, ast.Keyword):
keyword, value = self.visit(arg)
if keyword in kwargs:
raise TypeError, "%s() got multiple values for keyword
argument '%s'" \
% (func,keyword)
kwargs[keyword] = value
else:
posargs.append(self.visit(arg))
posargs.extend(node.star_args or [])

return self.getObject(func(*posargs,**kwargs))

def visitKeyword(self,node,**kw):
return node.name, self.visit(node.expr)

# Miscellaneous

def visitBackquote(self, node, **kw):
return repr(self.visit(node.expr))

# Function/class definition

def visitLambda(self, node, **kw):
raise NotImplementedError, "Lambda"

# Iterator evaluations

def visitGenExpr(self,node,*kw):
raise NotImplemetedError, "GenExpr"
def visitListComp(self,node,*kw):
raise NotImplemetedError, "ListComp"

# Some unexpected node type
def default(self, node, **kw):
raise Eval_Error("Unsupported source construct",
node.__class__,node)


def r_eval(source, context = None):
"""eval partial replacement,

Does not implement:
List Comprehensions, Generator Expressions, Lambda. Ellipsis

"""

walker = Eval(context or globals())
try:
ast = compiler.parse(source,"eval")
except SyntaxError, err:
raise
try:
return walker.visit(ast)
except Eval_Error, err:
raise
class tests(object):

def run(self):
"""Run all the tests"""
for name in dir(self):
if name.startswith("test_"):
getattr(self,name)()
print "%s: OK" % name

def test_const(self):
cases = ["""[1, 2, 'Joe Smith', 8237972883334L, # comment
{'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment
'xyzzy', [3, 5, [3.14159, 2.71828, []]]]"""]
for case in cases:
assert eval(case) == r_eval(case)

def test_algebra(self):
"""Show that r_eval matches eval on constant expressions"""
cases = [
"1+2/3 * 4.0 ** 5 % 2",
"(4 << 2 | 67 >> 2) ^ 0xFF",
]
for case in cases:
assert eval(case) == r_eval(case)
def test_names(self):
cases = [
"sum",
"sys.modules['os']",
]
for case in cases:
assert eval(case) == r_eval(case)

def test_calling(self):
cases = [
"getattr(object, 'subclasses'.join(['_'*2]*2))",
"type('Name', dict = {'a':1}, bases = (object,)).a",
"type(**dict(dict = {'a':1}, name = 'Name', bases = (object,))).a"
]
for case in cases:
assert eval(case) == r_eval(case)
def testall():
tests().run()

Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: questioner | last post by:
Hi folks, Id appreciate if you can help: I want to start an exe which takes as an argument filename. What I tried was: os.spawnl(os.P_NOWAIT,('processor.exe'),'filename.ext')) I also...
3
by: Alastair | last post by:
Hello guys, I've been building a search facility for an intranet site I'm part of developing and we've been building a search engine using Index Server. It mostly works, however there have been...
11
by: Marc Le Roy | last post by:
Hello, ADA Ravenscar is a restricted subset of the ADA language that has been defined for real-time software development in safety critical applications. Completed with additional restrictions...
4
by: KatB | last post by:
Hi, I'm creating an asp.net application and one of the functions I need is to click on a "Where Is This Office Located?" button. In a table, each employee will have an office code location...
8
by: DQ dont quit | last post by:
I'm currently working on a ASP.Net / C# / SQL 2000 project that involves the entering of keywords, that a web user enters, and then searching MSWord documents for those words. This information...
3
by: moi | last post by:
Hello, When user write a decimal number in a textbox with the numeric pad, he hits the "." button but in FRANCE, we use the ",". How to change the "." in the textbox with a "," ? Example : user...
4
by: andreas | last post by:
F.e. I want to make a stringvariable str = "nr1 nr2 nr3" that it should display like "nr1 nr2 nr3" str = """ & str & """ do not work. Thanks for any response
11
by: Bruce Lawrence | last post by:
Ok, I'm baffled... I'm making a query in access 97 between 2 tables. There is a field in both tables called "DWGNO". OPENORD has a record with a DWGNO of "00000012345" DIEDATA has a record...
1
by: unamas | last post by:
hi, Good day! Anyone generous enough to help me with this query. Anyway, I have a random acount number of 1, 2, 3, 4, 5 and i wanna get the results after this number in a table. Select...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.