天天看点

python基本数据类型

python标准数据类型

有六个标准的数据类型:

1、Number(数字)

2、String(字符串)

3、tuple(元组)

4、list(列表)

5、dict(字典)

6、Sets(集合)

python数据类型分类

可变数据:

字典、列表

不可变数据:

数字、字符串、元组、集合

python数据类型介绍

Number

python3支持float、int、complex、bool

在python3中只有一种类型int,表示长整型,没有python2中的long

示例:

a,b,c,d = 1.1,1,1+3j,True           

可以用type查看:

>>> map(lambda x:type(x),[1,1.1,1+3j,True])
[<type 'int'>, <type 'float'>, <type 'complex'>, <type 'bool'>]           

也可以用instance:

>>> isinstance(1.1,float)
True           

String字符串

字符串或串(String)是由数字、字母、下划线组成的一串字符。

以字母、数字、下划线组成的一串字符

它是编程语言中表示文本的类型

定义字符串:
>>>a = 'stringtype'
取出字符串:
>>>>>>a
'stringtype'
截取前5位字符:
>>>a[0:5]   从0开始,但截止到5之前
'strin'
截取最后一位字符:
>>>a[-1:]
'e'           

列表

列表用“[]”赋值

列表是使用最频繁的一种数据类型。

截取的方式也可以用【开始:结束】来截取

>>> data = [1,2,3,5,6,2,1,4]
>>> data[0:2]
[1, 2]           

元组

>>> a = (1,2,3,4,5)
>>>
>>> a[0:3]
(1, 2, 3)
尝试改变,但是是失败的:
>>> a[2] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment           

字典

>>> a = {'a':'b','c':'d','b':'a'}
>>> a
{'a': 'b', 'c': 'd', 'b': 'a'}
也可以用dict函数赋值:
>>> a = dict([('a','b')])
>>> a
{'a': 'b'}           
a = {}
或
a = dict()