5

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?

Prasath
  • 595
  • 5
  • 11

3 Answers3

15
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'>
perreal
  • 94,503
  • 21
  • 155
  • 181
  • Will work for most "primitive" types. Won't work for anything more complex, such as trying to get the type of a variable which happens to be a function object (like a lambda). – 2rs2ts Jul 12 '13 at 22:07
8

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')
murftown
  • 1,287
  • 1
  • 10
  • 13
1

I would just try different types, in the right order:

>>> def detect(s):
...     try:
...         return type(int(s))
...     except (TypeError, ValueError):
...         pass
...     try:
...         return type(float(s))
...     except (TypeError, ValueError):
...         pass
...     return type(s)
... 
>>> detect('3')
<type 'int'>
>>> detect('3.4')
<type 'float'>
>>> detect('foo')
<type 'str'>
jterrace
  • 64,866
  • 22
  • 157
  • 202
  • 2
    Caveat: You have to do `int` before `float` otherwise you could do `float(1)` and it'd be just fine. – 2rs2ts Jul 12 '13 at 22:10