Jump to content
adisharma

How To Convert A String To A Number In Python?

Recommended Posts

Hello Everyone,

 

I am confused about convert string to a number. Can anyone check this code is it right? Any suggest which is the best way to learn python in depth. 

 

print int("1") + 1

The above prints 2.

 

 

Share this post


Link to post

In general:

eval() will turn a string into a non-string: real, integer, object, etc.

repr() will turn a non-string into a string

 

As you noticed in your example you can also be specific about how you're converting a string, but I find eval() usually does the trick.

 

Share this post


Link to post
On 9/12/2019 at 9:21 AM, adisharma said:

Hello Everyone,

 

I am confused about convert string to a number. Can anyone check this code is it right? Any suggest which is the best way to learn python in depth. 

 

print int("1") + 1

The above prints 2.

 

 

 

Just to be picky: that is print from Python 2. In Python 3 you need parentheses:

print(int("1") + 1)

 

As for tutorials, I would start with the official one of the Python documentation (here the Python 3.5 version, as VW uses Python 3.5.2): https://docs.python.org/3.5/tutorial/index.html

Share this post


Link to post

ast.literal_eval(node_or_string)

 

You can convert a Python string to an int by using ast.literal_eval() . This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions , for example involving operators or indexing.

 

import ast

ast.literal_eval("111")

 

return  111

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


 

7150 Riverwood Drive, Columbia, Maryland 21046, USA   |   Contact Us:   410-290-5114

 

© 2018 Vectorworks, Inc. All Rights Reserved. Vectorworks, Inc. is part of the Nemetschek Group.

×
×
  • Create New...