开发者

Telling what type of data is what, Python

开发者 https://www.devze.com 2023-02-08 18:52 出处:网络
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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消