Computer >> Computer tutorials >  >> Programming >> Python

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


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
4

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'>