文件处理
f = file('m.txt', 'r')
for line in f.readlines():
line = line.strip('\n').split(':')
print line #print 可以打印字符串也可以打印list
print abc, 这样可以不换行 f.read 方法可以处理一种特殊情况,当f.read读到文件结尾时,如果文件在结尾增加内容,再次f.read()则可以读取刚才增加的内容
字符串
string.zfill(width) 返回一个长度为width的string,不足左边补0 str + str2 连接 str * 4 重复 str[1:4] 截取 “h" in str 成员运算符 - 如果字符串中包含给定的字符返回 True "My name is %s and weight is %d kg!" % ('Zara', 21) 格式化
str.capitalize 首字符大写 str.center(width)返回一个str居中,长度为width,左右用0填充的字符串 str.count(xx) 返回子串xx在str中出现的次数 str.decode('utf-8') 以 encoding 指定的编码格式utf-8 解码 string str.encode('utf-8') 以encoding指定的编码格式utf-8编码str
列表-list
列表就是c中的数组,php中的无key数组 list.count(x) 统计某个元素在列表中出现的次数 list.append(x) 在列表结尾追加元素x list.extend(list2) 在列表结尾追加一组元素list2 list.index(x) 在列表中找出x第一次出现的位置 list.insert(index, x) 插入元素 list.pop(index=-1)移除一个元素,并返回,默认最后一个 list.remove(obj) 移除列表中某个值的第一个匹配项 list.reverse 倒排 list.sort 排序 按值的字典排序 len(list) 返回长度 list + list2 组合 list * 4 返回一个重复4次list的元素的 list x in list 返回True 或 False for i in list: print i 遍历 list(tuple) 把元组list 转换为列表
元组
元组是一种常量数组 tuple = (1, 2, 3) 删除元组 del tuple tuple(x) 把列表x 转换为元组 任意无符号的对象,以逗号隔开,默认为元组, print 1,2,3
字典
字典是可变容器 x = {'a':1, 'b':'cccc'} 访问字典 print x['a'],修改 x['a'] = 'bbbbb' 删除元素 del x['a'] 删除字典 del x cmp(dict1, dict2) 比较 len(dict) 计算长度 str(dict) 输出字典的字符串表示 dict.clear() 清空字典 dict.copy() 浅复制 dict.fromkeys(seq, val) 创建一个新字典,key为seq中的key,值统一为val dict.get(key)返回指定的值 dict.has_key 如果键在字典dict里返回true,否则返回false dict.items() 返回一个二维列表,每个元素是一个子列表[key,value] dict.keys() 返回一个列表,包含dict所有的key 遍历 for i in list: #只会遍历key, 效率高 for k,v list.items() : 同时遍历 dict.values() 返回所有的value dict.pop(key) 删除指定的key,返回对应的值 dict.popitem() 随机删除并返回一组key,value
集合
定义集合 x = {'a', 'b', 'a'} x = set(['a', 'b', 'a', 'b']) x.add('c')为集合添加一个元素 x.clear 清空集合 x.copy 复制一个集合 x.difference()返回多个集合的差集 x.difference_update(y) 移除集合中的元素,这些元素在y集合中也存在 x.discard(y) 删除一个元素 x.intersection(y) 交集 x.pop 随机移除一个元素 x.remove(y) 如果y存在则移除,不存在则报错 x.union(y) 并集 x.update(y) 给集合x添加元素,y是一个集合