## Python Evaluation of Strings

Python code:

`nums = [1,2,3,4]`

equation = '+'.join(nums)

# yields '1+2+3+4' with type(equation) string

How to evaluate this? A simple `int(equation) will not give you the answer of 10 that you want...`

Answer: `eval(equation)`

will give you the right answer.

Special newb Treatment:

# prints 10

print eval('1+2+3+4')

Advertisements

*Lazsays:If nums is a list of integers, this will fail – join works only with strings. But with integers it’s easier (and faster) to use reduce:

| Posted 8 years, 10 months ago>>> nums = [1, 2, 3, 4]

>>> reduce( lambda a, b: (a + b), nums )

10