Python Programming

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


Trackbacks & Pingbacks


  1. * Laz says:

    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:
    >>> nums = [1, 2, 3, 4]
    >>> reduce( lambda a, b: (a + b), nums )

    | Reply Posted 9 years, 7 months ago

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: