Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of data stored in a string in python

Tags:

python

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?

like image 490
Prasath Avatar asked Jul 12 '13 21:07

Prasath


2 Answers

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'>
like image 121
perreal Avatar answered Sep 27 '22 23:09

perreal


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')
like image 31
murftown Avatar answered Sep 27 '22 23:09

murftown