经常忘记python某些语法,记录下方便自己下次查询。
1.数据结构类:
set操作:set([])add,remove, in , not in
list 操作: list(xx), append ,insert(index,item), remove, del arr[index], pop()法删除
map操作: .has_key() , .keys()
str 操作: ",".join(arr) ,将arr 列表用“,”链接成字符串, int(xx) , str(xx),float(xx) , .startswith()
2. 中文编码类(gbk为例)
第二行声明编码:
# -*- coding: gbk -*-
定义中文字符变量 value =u'中文', 在代码中中文需统一成unicode进行各种比较操作。
读取中文文本: m=f.readline() msg=u'' msg+=m.decode("gbk") or msg+=unicode(m, "gbk")
print 中文变量: msg =u'中文' ,直接print msg 即可。
写入文本: msg=u'中文' f.write(msg.encode("gbk"))
3. pdb 调试
3.1.断点设置与消除
b 显示所有断点
b function...
b xx.py:110
disable/enable 1 (断点号)
3.2 普通操作
r, l , c, p ,s ,....
4. 简易过滤IP地址
rip = re.compile(r"(\d{1,3}\.){3}\d{1,3}")
5. opt 参数解析
from optparse import OptionParser
def getArgs():
usage = "usage:%prog [options] arg \n ....help INFO....."
parser = OptionParser(usage)
parser.add_option("-f","--file" ,dest = "tracefile",help = "read from the tracedata. ")
parser.add_option("-r","--redundancyControl",action="store_true",dest = "redundancyControl",help = "enable to ...; ")
options,args = parser.parse_args()
return parser,options,args
def checkArgs(parser,options,args):
global redundancyControl
redundancyControl = options.redundancyControl
global tracefile
if options.tracefile:
tracefile = options.tracefile
else:
print "-f ;no tracefile is specified!"
parser.print_help()
sys.exit(1)