Reputation: 4925
In JavaScript we have +number which converts a string into a number based on its value, as shown below:
x = '123' => +x returns 123
y = '12.3' => +y returns 12.3
Now if I use int in python it returns:
x = '123' => int(x) returns 123
y = '12.3' => int(y) returns 12 which is wrong as it should return 12.3
Whereas if I use float:
x = '123' => float(x) returns 123.0 which is wrong as it should return 123 only though I know 123.0 is same as 123 but I want to parse it to some other query language which identifies the numbers as mentioned above.
y = '12.3' => float(y) returns 12.3
Upvotes: 0
Views: 310
Reputation: 37317
JavaScript doesn't have types for integers like other languages (like C) do, so 123
in JS is really 123.0
stored as double but displayed without the decimals. (There's BigInt
if you want to learn further, but it would have been 123n
).
In Python, you can use literal_eval
to get the numeric (literal) value from a string representation:
import ast
ast.literal_eval("123") # -> 123 (int)
ast.literal_eval("123.") # -> 123.0 (float)
ast.literal_eval("123.0") # -> 123.0 (float)
Upvotes: 1
Reputation: 3155
If, for some reason you do not want to use literal_eval
, I want to offer another solution using regex
. There isn't a necessarily "pretty" built-in method in Python to convert str
representations of int
and float
to int
and float
respectively.
import re
def conv(n):
if isinstance(n, str) and len(n) > 0:
if re.match(r"^-{0,1}[0-9]+$", n):
return int(n)
elif re.match(r"^-{0,1}[0-9]+(\.|e)[0-9]+$", n):
return float(n)
return n
>>> conv("-123")
-123
>>> conv("123.4")
123.4
>>> conv("2e2")
200.0
Upvotes: 1