python中的数据类型怎么判断

33次阅读
没有评论

共计 851 个字符,预计需要花费 3 分钟才能阅读完成。

在 Python 中,可以使用 type() 函数来判断一个对象的数据类型。例如:

x = 5
print(type(x))  # 输出:<class 'int'>

y = 3.14
print(type(y))  # 输出:<class 'float'>

z = "Hello"
print(type(z))  # 输出:<class 'str'>

lst = [1, 2, 3]
print(type(lst))  # 输出:<class 'list'>

tpl = (4, 5, 6)
print(type(tpl))  # 输出:<class 'tuple'>

dct = {'a': 1, 'b': 2}
print(type(dct))  # 输出:<class 'dict'>

st = {1, 2, 3}
print(type(st))  # 输出:<class 'set'>

除了使用 type() 函数外,还可以使用 isinstance() 函数来判断一个对象是否属于某个特定的数据类型。例如:

x = 5
print(isinstance(x, int))  # 输出:True

y = 3.14
print(isinstance(y, float))  # 输出:True

z = "Hello"
print(isinstance(z, str))  # 输出:True

lst = [1, 2, 3]
print(isinstance(lst, list))  # 输出:True

tpl = (4, 5, 6)
print(isinstance(tpl, tuple))  # 输出:True

dct = {'a': 1, 'b': 2}
print(isinstance(dct, dict))  # 输出:True

st = {1, 2, 3}
print(isinstance(st, set))  # 输出:True

这些函数在判断数据类型时非常有用,可以帮助我们编写更加健壮和灵活的代码。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计851字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)