Python数据类型

145 阅读1分钟

如何在Python中判断变量类型

Python3 基本数据类型

  1. 数字
    • 整型(int)
    • 长整形(long)
    • 浮点数(float)
    • 复数(complex)
  2. 字符串(str)
  3. 布尔值(bool)
  4. 列表(list)
  5. 元组(tuple)
  6. 字典(dict)
  7. 集合(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