Avec python vous pouvez déterminer le type de variable avec la fonction type(), illustration:
>>> x = 3>>> type(x)<type 'int'>>>> x = 3.2>>> type(x)<type 'float'>>>> x = 'Hello World !'>>> type(x)<type 'str'>
Vous pouvez alors créer des conditions utilisant le type de la variable:
>>> x = 'Hello World !'>>> type(x) is strTrue>>> if type(x) is str:... print "do something"...do something
Autre possibilité avec la fonction "built-in" isinstance()
>>> i = 1>>> f = 0.3>>> s = 'Hello'>>> l = [1,2,3]>>> d = {0:'bob',1:'bill'}>>> t = (0,1,2)>>> isinstance(i,int)True>>> isinstance(i,float)False>>> isinstance(f,float)True>>> isinstance(s,str)True>>> isinstance(l,list)True>>> isinstance(e,bool)True>>> isinstance(d,dict)True>>> isinstance(t,tuple)True
Recherches associées
| Liens | Site |
|---|---|
| type() | Python Doc |
| How to determine the variable type in Python? | stackoverflow |
| isinstance() | python doc |
| Python: Checking Type of Variable | choorucode |
