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\"]
<
A variant of ryans's nice solution, for numpy users:
def tonum( x ):
""" -> int(x) / float(x) / None / x as is """
if np.isscalar(x): # np.int8 np.float32 ...
# if isinstance( x, (int, long, float) ):
return x
try:
return int( x, 0 ) # 0: "0xhex" too
except ValueError:
try:
return float( x ) # strings nan, inf and -inf too
except ValueError:
if x == "None":
return None
return x
def numsplit( line, sep=None ):
""" line -> [nums or strings ...] """
return map( tonum, line.split( sep )) # sep None: whitespace