ValueError: malformed string when using ast.literal_eval

0 votes

It is widely known that using eval() is a potential security risk so the use of ast.literal_eval(node_or_string) is promoted

However In python 2.7 it returns ValueError: malformed string when running this example:

>>> ast.literal_eval("4 + 9")

Whereas in python 3.3 this example works as expected:

>>> ast.literal_eval('4+9')
13

Why does it run on python 3 and not python 2? How can I fix it in python 2.7 without using the risky eval() function?

May 27 in Python by kartik
• 20,470 points
1,092 views

1 answer to this question.

0 votes

Hello Kartik,

An updated version of the answer from @poke that allows negative numbers in py3.x or other unary operators. So "-3" evaluates to -3 for example, rather than an error.

import ast, operator

binOps = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Mod: operator.mod
}

unOps = {
ast.USub: operator.neg
}

node = ast.parse(s, mode='eval')

def arithmetic_eval(s):
    binOps = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.Mod: operator.mod
    }

    unOps = {
    ast.USub: operator.neg
    }

    node = ast.parse(s, mode='eval')

    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        elif isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Num):

Hope this work!!

answered May 27 by Niroj
• 43,540 points

Related Questions In Python

0 votes
1 answer

When I create and remove files rapidly on windows using python I get WindowsError (Error 5)

Here's the short answer: disable any antivirus or ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,780 points
567 views
0 votes
1 answer

Getting some errors regarding python when using sublime text

I don't know if you still need ...READ MORE

answered Sep 7, 2018 in Python by charlie_brown
• 7,780 points
66 views
0 votes
1 answer
0 votes
1 answer

How to put a variable inside a String using Python?

In the easiest way, you can create ...READ MORE

answered Nov 23, 2018 in Python by Nymeria
• 3,520 points

edited Dec 12, 2018 by Nymeria 102 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,190 views
0 votes
0 answers
0 votes
1 answer

Error: when install pylibmc using pip

Hello @kartik, It's in the libmemcached package. To ...READ MORE

answered May 20 in Python by Niroj
• 43,540 points
221 views
0 votes
1 answer

Error:SSL backend error when using OpenSSL

Hii @kartik, After reading their INSTALLATION file, I ...READ MORE

answered May 20 in Python by Niroj
• 43,540 points
226 views