In Python, how can I parse a numeric string like \"545.2222\"
to its corresponding float value, 545.2222
? Or parse the string \"31\"
t
Pass your string to this function:
def string_to_number(str):
if("." in str):
try:
res = float(str)
except:
res = str
elif(str.isdigit()):
res = int(str)
else:
res = str
return(res)
It will return int, float or string depending on what was passed.
string that is an int
print(type(string_to_number("124")))
string that is a float
print(type(string_to_number("12.4")))
string that is a string
print(type(string_to_number("hello")))
string that looks like a float
print(type(string_to_number("hel.lo")))