I would like to be able to tell if a variable is an 开发者_高级运维int or not using an if statement in Python. How would I go about this.
Use isinstance
:
if isinstance(var, int):
print "Int"
elif isinstance(var, str):
print "Str"
else:
print "Other:", type(var)
if isinstance(x,int):
print 'win'
You just need to use isinstance:
value = 123
if isinstance(value, int):
print "Int"
else:
print "Not Int"
If the question is to detect if a variable in bound to an int
or a value of any derived type, so isinstance
is the solution...
... but it does not distinguish between say int
and bool
.
In Python 3:
>>> isinstance(123, int)
True
>>> isinstance(True, int)
True
>>> isinstance(123, bool)
False
>>> isinstance(True, bool)
True
If you really need to know if a value is an int
and nothing else, type()
should be the way to go:
>>> type(123)
<class 'int'>
>>> type(123) == int
True
精彩评论