Python: how do I check the variable type?


I am a python-pro,i have passion for this language, python. Well
First of all
>>> myvar = "hello"
>>> len(myvar) 
4
>>> myvar2 = ["hello","world"]
>>> len(myvar2)
2
Then I realised there is a simple (and cleaner) way of doing what I wanted:
>>> type(myvar2)
<type 'list'>
>>> type(myvar2)
<type 'str'>
Lets imagine you want to make a conditional statement taking into account the type of a variable. Here is how you do it:
if type(myvar).__name__ == 'str':
    print "myvar is a string!"
elif type(myvar).__name__ == 'list':
    print "myvar is a list!"

0 comments :