获取值的类型可以使用type()方法:
type(50),type("50"),type([5,5]),type({5:5})
分别可以得到
<class 'int'>,<class 'str'>,<class 'list'>,<class 'dict'>
判断值的类型仍然可以使用type()方法:
值的类型是int,打印true
if type(50) is int:
print("是int")
值的类型不是str,打印false
if type(50) != str:
print("不是str")
判断值的类型还可以使用isinstance(50,int),直接返回True或者False
值的类型是int,打印结果
if isinstance(50, int):
print("是int")
值的类型不是str,打印结果
if not isinstance(50, str):
print("不是str")
本文介绍了如何使用Python的type()函数获取并判断变量类型,如int、str、list和dict,并对比了type()和isinstance()的用法,重点讲解了这两种方法在实际编程中的应用场景和区别。

被折叠的 条评论
为什么被折叠?



