Skip to content

Instantly share code, notes, and snippets.

@alyssonbruno
Created July 25, 2012 15:17
Show Gist options
  • Save alyssonbruno/3176731 to your computer and use it in GitHub Desktop.
Save alyssonbruno/3176731 to your computer and use it in GitHub Desktop.
Verificando expressão numérica
def eval_expr(text):
test_char = lambda c: c in '1234567890.,*/+-()'
for char in text:
if not test_char(char):
raise Exception('Invalid Char in String')
return long(eval(text,{},{}))
@perone
Copy link

perone commented Jul 25, 2012

Entendi, mas você pode usar o string.digits e também remover a função lambda.

@santagada
Copy link

não testei, mas faria algo assim:

import re
def eval_expr(text):
    if not re.match('^[-0-9.,*/+()]*$'):
            raise ValueError('Invalid char in string')
    return eval(text, {}, {})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment