In this tutorial we are going to use Python to parse a numeric strings with values like 3.14522567
and cast it to a float number.
In cases where the string has an integer value like 15
we are going to cast it to 15 integer number.
Using string methods
Python string has the isdigit method which will return True if if all characters in the string are digits and there is at least one character, false otherwise. isdigit will help us to solve the string to integer problem.
For float number we will use a custom function:
def isfloat(value):
try:
# we try to conver the string to float.
float(value)
return True
except ValueError:
# the was a cast exception
# we return false the string
# value is not a float
return False
So out final function will be:
def give_me_a_number(string_with_numeric_value):
if string_with_numeric_value.isdigit():
return integer(string_with_numeric_value)
elif isfloat(string_with_numeric_value):
return float(string_with_numeric_value)
raise ValueError("Can't convert string to integer or float")
Note : that our function is not optimized, we are converting the float twice. Note 2: We first check for integer and then for float, since if we first check for float an integer will be converted to float.
Using regular expression to check for float
This is an overkill solution but it's interesting to know the regex to match a float:
import re
if re.match("^\d+?\.\d+?$", string_with_possible_float_value) is None:
print("String is not a float number")