Is there any way to understand what data type that a string holds... The question is of little logic but see below cases
varname = '444'
somefunc(varname) => int
varname = 'somestring'
somefunc(varname) => String
varname = '1.2323'
somefunc(varname) => float
My Case: I get a mixed data in a list but they're in string format.
myList = ['1', '2', '1.2', 'string']
I'm looking for a generic way to understand whats their data so that i can add respective comparison. Since they're already converted to string format, I cant really call the list (myList) as mixed data... but still is there a way?
from ast import literal_eval
def str_to_type(s):
try:
k=literal_eval(s)
return type(k)
except:
return type(s)
l = ['444', '1.2', 'foo', '[1,2]', '[1']
for v in l:
print str_to_type(v)
Output
<type 'int'>
<type 'float'>
<type 'str'>
<type 'list'>
<type 'str'>
You can use ast.literal_eval() and type():
import ast
stringy_value = '333'
try:
the_type = type(ast.literal_eval(stringy_value))
except:
the_type = type('string')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With