How do we evaluate a string and return an object in Python?

PythonServer Side ProgrammingProgramming

The built in eval() function requires a string argument. However Python interpreter treats the string as a Python expression and evaluates if it is valid and then returns the type object resulting from expression.

String containing arithmetic expression

>>> x=eval('2+2')
>>> type(x)
<class 'int'>
>>> x

String evaluating to list/tuple

>>> x=eval('tuple([1,2,3])')
>>> x
(1, 2, 3)
>>> type(x)
<class 'tuple'>

String containing list comprehension expression

>>> x = eval('list((a*2 for a in range(5)))')
>>> x
[0, 2, 4, 6, 8]
>>> type(x)
<class 'list'>

Published on 06-Feb-2018 07:02:16