python怎么判断数据类型


当前第2页 返回上一页

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

#判断变量类型的函数

  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

#返回变量类型

  def getType(variate):

    arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}

    vartype = typeof(variate)

    if not (vartype in arr):

        return "未知类型"

    return arr[vartype]

     

#判断变量是否为整数

money=120

print("{0}是{1}".format(money,getType(money)))

#判断变量是否为字符串

money="120"

print("{0}是{1}".format(money,getType(money)))

money=12.3

print("{0}是{1}".format(money,getType(money)))

#判断变量是否为列表

students=['studentA']

print("{0}是{1}".format(students,getType(students)))

#判断变量是否为元组

students=('studentA','studentB')

print("{0}是{1}".format(students,getType(students)))

#判断变量是否为字典

dictory={"key1":"value1","key2":"value2"}

print("{0}是{1}".format(dictory,getType(dictory)))

#判断变量是否为集合

apple={"apple1","apple2"}

print("{0}是{1}".format(apple,getType(apple)))

返回:

w.png

isinstance() 与 type() 区别:

type() 不会认为子类是一种父类类型,不考虑继承关系。

isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

以上就是python怎么判断数据类型的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python中下划线怎么打

Python基础入门--函数

Python list有序吗

了解Python中np是做什么的

Python中divmod函数的用法是什么?

Python有switch语句吗

Python语言的面向对象编程的介绍(附代码)

eval在Python什么意思

Python怎么随机产生一个范围内的数

Python能做什么?是什么意思?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...