您的位置:首页 > 编程语言 > Python开发

3.1 python中的数据类型 [python入门教程]

2014-02-03 12:27 591 查看
当我们创建一个变量时,系统会自动创建该变量的对象,该对象有三个属性值:身份id、类型type和值。id可以理解为该对象在内存中的地址(实际上不是),或者一栋房子对应的门牌号,示例:

>>> a=5
>>> id(a)
10415032
>>> type(a)
<type 'int'>
>>> a
5


主要数据类型:

Number(数字) 包括int,long,float,double,complex

String(字符串) 例如:hello,"hello",hello

List(列表) 例如:[1,2,3],[1,2,3,[1,2,3],4]

Dictionary(字典) 例如:{1:"nihao",2:"hello"}

Tuple(元组) 例如:(1,2,3,abc)

File(文件) 例如:f = open(a.txt,rw)

类型转换:

ord() 将字符转换成ASCII

chr() 将ASCII转换成字符

hex() 将整数转换成十六进制

oct() 将整数转换成八进制

bin() 将整数转换成二进制

还有其他的如int(),str()

1. 数字类型: 包括很多内置类型及第三方提供的类型: Integer, Long, Boolean, Float, Complex, Decimal
2. set
>>> x=set("aabc")
>>> x
>>> set(['a','c','b'])
>>> y=set("abc")
>>> x==y, x is y
>>> (True, False)
3. 字符串
>>> x="abc"
>>> y='abc'
>>> z=str('abc')
>>> print x == z
>>> True
>>> print x is z
>>> True
>>> x[0]
>>> 'a'
>>> x[0] = 'd'
>>> TypeError: 'str' object does not support item assignment
4. 列表
>>> x=[1,2]
>>> y=list([1,2])
>>> print x==y
>>> True
>>> print x is y
>>> False
5. 字典
>>> x={1:"foo", 2:"bar"}
>>> y=dict({1:'foo',2:'bar'})
>>> print x.__cmp__(y)
>>> 0
>>> print y.__eq__(x)
>>> True
6. 元组
>>> x=(1,2,3)
>>> y=tuple((1,2,3))
>>> x==y, x is y
>>> (True, False)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: