given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have:
[\"hello\", \"3\", \"3.64\", \"-1\"]
<
If the you are truly interested in only strings, floats, and ints, I prefer the more verbose, less-evalful
def interpret_constant(c):
try:
if str(int(c)) == c: return int(c)
except ValueError:
pass
try:
if str(float(c)) == c: return float(c)
except ValueError:
return c
test_list = ["hello", "3", "3.64", "-1"]
typed_list = [interpret_constant(x) for x in test_list]
print typed_list
print [type(x) for x in typed_list]