Python 判断变量的数据类型

本文介绍了Python中使用type()和isinstance()进行变量类型的检查,并提供了一种判断输入是否为数字的方法。通过实例演示了如何判断整数、字符串及None类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原网址:http://blog.youkuaiyun.com/gukesdo/article/details/7064868

import types
aaa = 0
print type(aaa)
if type(aaa) is types.IntType:
    print "the type of aaa is int"
if isinstance(aaa,int):
    print "the type of aaa is int"

bbb = 'hello'
print type(bbb)
if type(bbb) is types.StringType:
    print "the type of bbb is string"
if isinstance(bbb,str):
    print "the type of bbb is string"

#if the type is NoneType,the isinstance does not work
#we should judge the NoneType like below
#if row is None
#if type(row) is types.NoneType

#In my opinion,use the types to judge the type of a param is convinient<span style="font-family:Arial;background-color: rgb(255, 255, 255);">, use the isinstance to judge whether a instance is a type of a class or not</span>

=============================================================

判断输入是否为数字的方法(不考虑是整型还是浮点型):

#将变量转换为float型,如果能成功则是数字,如果抛出错误则不是数字。
#代码如下
def isisnumber(a):
    try:
        float(a)
        return 'is number' #能成功转换为浮点型,则是数字
    except:
        return 'not number' #不能成功转换为浮点型,则不是数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值