I'm trying to convert string to numbers. It can be float, integer, or empty string.
def num(s):
if not s: return ""
try:
return int(s)
except ValueError:
return float(s)
else: return 0
str1 = ""
str2 = "0.0"
str3 = "1.1"
str4 = "10"
print("str1 = "+str(num(str1)))
print("str2 = "+str(num(str2)))
print("str3 = "+str(num(str3)))
print("str4 = "+str(num(str4)))
so, the output:
str1 = <== OK
str2 = 0.0 <== I need this as integer 0
str3 = 1.1 <== OK
str4 = 10 <== OK
anyone can help?
'0.0'be converted to0, not0.0, when it clearly represents the latter?floatto anint, since JSON defines aninttype and that clearly is not anint.jsonmodule instead of rolling your own function?