如何在Python中判断变量类型
Python3 基本数据类型
- 数字
- 整型(int)
- 长整形(long)
- 浮点数(float)
- 复数(complex)
- 字符串(str)
- 布尔值(bool)
- 列表(list)
- 元组(tuple)
- 字典(dict)
- 集合(set)
判断变量类型的方法
1. isinstance(会认为子类是一种父类类型,考虑继承关系)
def typeof(variate):
type=None
if isinstance(variate,int):
type = "int"
elif isinstance(variate,str):
type = "str"
elif isinstance(variate,float):
type = "float"
elif isinstance(variate,list):
type = "list"
elif isinstance(variate,tuple):
type = "tuple"
elif isinstance(variate,dict):
type = "dict"
elif isinstance(variate,set):
type = "set"
return type
2. type(不会认为子类是一种父类类型,不考虑继承关系)
def typeof(variate):
type1 = ""
if type(variate) == type(1):
type1 = "int"
elif type(variate) == type("str"):
type1 = "str"
elif type(variate) == type(12.3):
type1 = "float"
elif type(variate) == type([1]):
type1 = "list"
elif type(variate) == type(()):
type1 = "tuple"
elif type(variate) == type({"key1":"123"}):
type1 = "dict"
elif type(variate) == type({"key1"}):
type1 = "set"
return type1