[Tutor] Getting the type of a variable

Glenn T Norton gtnorton at earthlink.net
Fri Oct 27 15:22:41 CEST 2006


Etrade Griffiths wrote:

>Hi
>
>I want to check the type of a variable so that I know which format to use 
>for printing eg
>
>def print_correct_format(a):
>
>	if type(a) == 'int':
>		print "a is an integer, value %i" % (a)
>	elif type(a) == 'float':
>		print "a is a float, value %f" % (a)
>	else:
>		print "a is unknown type"
>
>The comparison type(a) == 'int' etc does not work - I'm sure there's a 
>simple way to fix this but can't see it at the moment - any suggestions?
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
You have two options here, but the idea is, you have to compare type to 
type, not type to string
say a is an integer
a = 5

type(a) == type(1)
True

or a is a string
type(a) == type('')


or you can use the types module

import types

x = 1
type(x) == types.IntType
True

x = 'String'
type(x) == types.StringType
True


Good Luck,
Glenn



-- 
"Ketchup. For the good times... " - Ketchup Advisory Board 
Glenn Norton
Application Developer
Nebraska.gov
1-402-471-2777
glenn at nebraska.gov



More information about the Tutor mailing list