python基础学习(二):数据类型

来源:互联网 发布:python 内容管理系统 编辑:程序博客网 时间:2024/06/07 04:52

1.python常用的数据类型有整形(int),浮点型(float),布尔型(bool),字符串(str)


他们之间可以转化:

>>> a="520"

>>> b=int(a)
>>> b
520
>>> b=float(a)
>>> b
520.0
>>> c=str(a)
>>> c
'520'
>>> a=5e19
>>> b=str(a)
>>> b

'5e+19'


转化时注意问题:

(1)像这种根本无法转换的类型进行转换时会发生错误:

>>> a='lucy'
>>> b=int(a);
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    b=int(a);
ValueError: invalid literal for int() with base 10: 'lucy'

(2)不可跳跃转化

a='5.12'
>>> b=int(a)
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    b=int(a)
ValueError: invalid literal for int() with base 10: '5.12'

字符串‘5.12’只能先转换成float型,再转化为int,如下

>>> a='5.12'

>>> b=float(a)
>>> b
5.12

>>> c=int(b)
>>> c
5


另外注意科学计数法如 4e13也是属于float


2.获得数据类型type()

>>> a="asdfg"
>>> type(a)
<class 'str'>
>>> type(12.3)
<class 'float'>


3.验证某变量是不是某类型isinstance(variable,datatype)

>>> a='asdfg'
>>> isinstance(a,str)
True
>>> isinstance(12.3,float)
True
>>> isinstance(12.33.int)
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    isinstance(12.33.int)
AttributeError: 'float' object has no attribute 'int'

1 0