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

python数据类型与运算符

2011-09-19 10:20 323 查看
一、概括

1.1、python中所有的类型都是类类型,内置数据类型和用于定义的类型具有相同的结构,说其为内置类型的原因是其属性、方法都是python预先定义好的。

1.2、python虽然是动态语言,但是隐式转换是有限的,这样做的目的是使程序的可读性和可维护性提高。

二、数值类型

int long(有符号整数,int 和 long由python自动处理,long型范围取决于内存大小,9L(9l)的类型为long)

bool(True and False)

float(范围取决于内存大小)

complex(1+2j)

数值类型对象是不可变对象,修改其值相当于创建另一个对象。

#coding=utf-8

num1=100
num2=True
num3=3.6
num4=1+2j

print(num1+num2+num3+num4)

print 2**(1+2j)

#数值类型可以应用任意的算术运算发,并且系统可以进行隐式转换
三、序列类型

序列类型有字符串类型,列表类型,元组类型,它们具有很多共通的方法属性。

3.1、字符串

单引号字符串和双引号字符串无区别,若要禁止转意字符可以用rR"\n\t"来表示。

字符串对象是不可变对象,修改其值相当于创建了另一个对象。

3.1.1、字符串对象的生成

#coding=utf-8

list1 =["s","t","r","i","n","g"]
tuple1=("s","t","r","i","n","g")

str1="string" #直接赋值
str2=str(list1) #构造函数
str3=str(tuple1)
str4=str(2)
str5=unicode(2)#unicode字符串
str6=chr(100)
str7=unichr(2000)
num1=ord(str7)

print num1

3.1.2、字符串对象的内置方法属性提供了常见的字符串处理方法,若需要更加强大的字符串处理可以使用正则库

#coding=utf-8

str1="string"

#修改字符串的值
str1.capitalize() #开头字母大写
str1.title()#同上
str1.lower() #转为小写
str1.swapcase() #反转大小写

str1.decode(encoding="utf-8") #把指定编码转换成utf-16编码
str1.encode(encoding="utf-8") #把utf-16编码转换成指定编码

str1.replace("s","S")
str1.split("t") #分成两个元素的元组
str1.splitlines()
str1.partition("t") #分成三个元素的元组
str1.rpartition("t")

#格式化相关
str1.center(10) #空格填充两端
str1.ljust(10) #左对齐
str1.lstrip() #截掉左边的空格
str1.rstrip() #截掉右边的空格
str1.strip() #截掉两边的空格
str1.zfill(10)#前面填充0

#查找相关
str1.find("t")#可以指定起始和结束位置
str1.rfind("t")#从右边查找
str1.index("x")#若不存在指定字符串则抛出异常
str1.rindex("x")
str1.count("t")

#字符串内容判断
str1.isalnum() #字母或数字
str1.isalpha() #字母
str1.isupper() #大写
str1.islower() #小写
str1.istitle() #第一个字母大写
str1.isspace() #空格
str1.isdigit() #0-9
str1.startwith("s")
str1.endswith("g")


3.2、列表 [1,2,3]

列表是可变对象。

3.3、元组 (1,2,3)

元组是不可变对象。

3.4、序列类型支持的共通操作

#coding=utf-8

str1="string"
list1 =["s","t","r","i","n","g"]
tuple1=("s","t","r","i","n","g")

print(str1[2],list1[2],tuple1[2]) #切片操作
print(str1[1:4:2],list1[1:4:2],tuple1[1:4:2])

print("s" in str1,"s" in list1,"s" not in tuple1) #存在判断

print(str1*2,list1+list1) #重复和连接
四、字典类型
python中hash数据类型,字典的键只能是不可变对象。

#coding=utf-8

dict1={"first":1,"second":2,"third":3}
dict2=dict((["first",1],["second",2],["third",3]))
dict3={}.fromkeys(("first","second","third"),100) #具有相同值的list
print dict3["second"]


五、其他内建类型对象

有些类型对象是解释器内部维护的,他们是

类型

Null 对象 (None)

文件

集合/固定集合

函数/方法

模块



六、运算符

6.1、算数运算符

+ - * / // % **

6.2、关系运算符

< <= > >= == !=

6.3、逻辑运算符

and or not

6.4、位运算符

取反(~),按位 与(&), 或(|) 及 异或(^) 及左移(<<)和右移(>>)

6.5、赋值和增量赋值运算符

+= -= *= /= %= **=

<<= >>= &= ^= |=

6.6、补充

复数不能使用关系运算符

位运算符只能用于整数类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: