Jump to content

How To Convert A String To A Number In Python?


adisharma

Recommended Posts

  • 2 weeks later...
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

Link to comment
  • 7 months later...

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

Link to comment

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.

×
×
  • Create New...