python 常见关键字和语法(备忘)

本文总结了Python中的常用语法,包括数据结构操作如set、list、map等的基本使用方法;介绍了中文编码处理技巧;演示了pdb调试工具的使用;提供了一个简易IP地址过滤的方法;最后展示了如何使用optparse进行命令行参数解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

经常忘记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)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值