python判断变量是否为数字、字符串、列表、字典等

您所在的位置:网站首页 python判断字母还是数字符号 python判断变量是否为数字、字符串、列表、字典等

python判断变量是否为数字、字符串、列表、字典等

2024-01-06 21:13| 来源: 网络整理| 查看: 265

copy from : https://www.jianshu.com/p/09d94bca8e54

在实际写程序中,经常要对变量类型进行判断,除了用type(变量)这种方法外,还可以用isinstance方法判断:

a = [1,2] if 'list' in str(type(a)): print('1') else: print('2') a = 1 b = [1,2,3,4] c = (1,2,3,4) d = {‘a‘:1,‘b‘:2,‘c‘:3} e = "abc" if isinstance(a,int): print "a is int" else: print "a is not int" if isinstance(b,list): print "b is list" else: print "b is not list" if isinstance(c,tuple): print "c is tuple" else: print "c is not tuple" if isinstance(d,dict): print "d is dict" else: print "d is not dict" if isinstance(e,str): print "d is str" else: print "d is not str"

作者:阿拉鸡 链接:https://www.jianshu.com/p/09d94bca8e54 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在实际写程序中,经常要对变量类型进行判断,除了用type(变量)这种方法外,还可以用isinstance方法判断:

a = [1,2] if 'list' in str(type(a)): print('1') else: print('2') a = 1 b = [1,2,3,4] c = (1,2,3,4) d = {‘a‘:1,‘b‘:2,‘c‘:3} e = "abc" if isinstance(a,int): print "a is int" else: print "a is not int" if isinstance(b,list): print "b is list" else: print "b is not list" if isinstance(c,tuple): print "c is tuple" else: print "c is not tuple" if isinstance(d,dict): print "d is dict" else: print "d is not dict" if isinstance(e,str): print "d is str" else: print "d is not str"

作者:阿拉鸡 链接:https://www.jianshu.com/p/09d94bca8e54 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3