rajini raja
rajini raja

Reputation: 99

How to evaluate an expression present within string?

Here I need to evaluate an expression present within string.

for eg,

>> a = '5 + 6'

>> a = 5 + 6

How to achieve this?

Upvotes: 0

Views: 42

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

You could use eval method by passing an expression as argument. The expression argument is parsed and evaluated as a Python expression.

a = eval('5 + 6')

Upvotes: 1

latika bhurani
latika bhurani

Reputation: 80

You can use eval() as it treats string as code.

a = '5 + 6'

eval(a)

Upvotes: 0

Related Questions