How to determine a variable's datatype?

Michal Bozon bozon at natur.cuni.cz
Thu Mar 16 14:24:13 CET 2000


On Wed, 15 Mar 2000, Peter Bittner wrote:

> Hi there!
> 
> Is it possible in Python to determine the datatype of an object?
> 
> E.g. (kind of like this)
>      var1 = 3
>      var2 = 'Hello'
>      var1.datatype   ==> yields "int"
>      var2.datatype   ==> yields "string" or list of characters
> 

You can use builtin function type:
>>> i = 123
>>> s = "spam"
>>> l = [1, "2", 10]
>>> d = {"Monty": "Python", "foo": "spam"}
>>> t = (1, 2, 3)

>>> type(i) == type(1)
1
>>> # It meant it is true
>>> type(i) == type("")
0
>>> # It meant it is false
>>> type(s) == type("")
1
>>> type(l) == type([])
1
# ...
# ...

So if you can use something like this:

if type(a) == type(1):
    print "a is integer"
if type(a) == type(""):
    print "a is string"

Michal Bozon
Faculty of Science, Charles Univ., Prague, Czech Rep.
bozon at natur.cuni.cz
http://www.natur.cuni.cz/~bozon




More information about the Python-list mailing list