python type函数和isintance函数 获取数据的数据类型
来源:互联网 发布:软件交易会 编辑:程序博客网 时间:2024/06/06 00:16
引言
有时候可能需要确定一个变量的数据类型, 例如用户的输入, 当需要用户输入一个整数, 但用户却输入一个字符串,就有可能引发一些意想不到的错误或者导致程序崩溃.
简言之, 就是程序设计过程中, 有时是需要确定变量的数据类型的, 不然可能会导致错误
获取数据类型
- python 可以通过type()函数来获取变量的数据类型
如:
>>> type(666) # 整数类型<class 'int'>>>> type('666') # 字符串类型<class 'str'>>>> type(66.666) # 浮点数类型<class 'float'>>>> type(True) # 布尔类型<class 'bool'>>>> type([66,66,66,666]) # 列表类型<class 'list'>>>> type((66,66,666,666)) # 元组类型<class 'tuple'>>>> type(range(5)) # range类型<class 'range'>
判断变量数据类型是否相等
- 方法一, 使用isinstance()函数 (推荐)
isintance()函数有两个参数, 第一个参数是待确定类型的数据, 第二个参数是指定一个数据类型, 若第一个参数的数据类型同第二个参数指定的数据类型, 返回 True, 否则返回False
>>> print(isinstance(6666, int))True>>> print(isinstance(6666, float))False>>> print(isinstance(6666., float))True>>> print(isinstance('6666', str))True
- 方法二, 使用type()函数
>>> a = 6666>>> b = '6666'>>> if type(a) == type(b):... print('Type of a and type of b is the same')... else:... print('Not the same')... Not the same>>>
阅读全文
0 0
- python type函数和isintance函数 获取数据的数据类型
- python 函数定义和内置函数isinstance以及数据类型检查type的使用
- 【python 】数据类型和返回数据类型的函数
- MySQL改变数据类型的函数CAST(x AS type)和CONVERT(x,type)
- Python的type, str, dir和callable函数
- python函数 cmp() type() str() repr()和 ''
- python type函数
- python type 函数
- python数据类型和3个重要函数
- python编程基础-数据类型和函数
- Python数据类型和相关函数方法
- Python函数---dir(),help(),type()
- python 获取当前位置所在的函数名和行号
- python 获取当前位置所在的函数名和行号
- python中获取当前位置所在的行号和函数名
- postgresql中获取json数据和聚合函数的使用
- python 获取当前函数名和行号
- 【Python】Python type()函数用途及使用方法
- Nodejs cluster模块深入探究
- arm neon 数据类型介绍
- java开发程序员必备技能
- E
- Hive 建表结合正则表达式的案例
- python type函数和isintance函数 获取数据的数据类型
- 学习笔记—HTML基础
- YII2(一)用YII2创建、迁移数据表 migrations
- SHUOJ Fibonacci数列
- 【noip 2015】联合权值
- 类的大小(sizeof)
- css四种导入方式
- 使用Makefile终端参数实现跨平台编译控制
- [LeetCode] 14. Longest Common Prefix