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

About these ads

Comments

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

    | Reply Posted 5 years, 7 months ago


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: