adisharma Posted September 12, 2019 Share Posted September 12, 2019 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. Quote Link to comment
JBenghiat Posted September 12, 2019 Share Posted September 12, 2019 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. Quote Link to comment
rohanjoshi0894 Posted September 25, 2019 Share Posted September 25, 2019 Here is the simple code which you need to follow: s = "1234" i = int(s) print i+1 Quote Link to comment
Nicolas Goutte Posted September 25, 2019 Share Posted September 25, 2019 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 Quote Link to comment
warrenfelsh Posted May 1, 2020 Share Posted May 1, 2020 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 Quote Link to comment
Recommended Posts
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.