免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 957 | 回复: 0
打印 上一主题 下一主题

python tips [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-10-25 15:10 |只看该作者 |倒序浏览
1. file operation
    fp = open("filename")
    line = fp.readline() //get line
    content = fp.read() //all content of file, that is, read to end
   
2. number
    8/9 = 0
    8/float(9) = 0.88888
3. sort list
    list=['a','e','b','c']
    sorted(list) // sort list
    len(list) //length of list
    for item in list:
        print item //access each item in list
4. sort dict
    dict={'a':2,'e':4,'b':2}
    sorted_keys = sorted(dict.keys())
    for key in sorted_keys:
        print dict[key] //first sort the key, then retrive value for each sorted key
    for k,v in dict.iteritems():
        print k, v // access every key and value
5. string
    import string
    range(start, end, step ) // end will not be contained
    range( 3, 1, -1 ) => 3 2
   
    int('2') //string to int
    str(2) //int to string
    'a'.isdigit() False
6. string format
    %-10s string type, left-pagged, 10 placehode
    print "%-10s %-20s" % ("sss", "tt")
    "sfsd".find('f') == 1
    "aab".replace("b","") == "aa"
7. datetime
    from datetime import datetime
    datetime.max //max datetime
    datetime.min //mindatetime
    datetime.strptime("Sun Oct 25 00:15:34 2009","%a %b %d %H:%M:%S %Y")
    datetime.weekday() //with ()
    datetime.month
    datetime.day
    datetime.hour
    datetime.minute
    datetime.second
    timedelta = datetime1 - datetime2
    all kinds of datetime format can be found:
    http://docs.python.org/library/datetime.html
    http://blog.csdn.net/suiyunonghen/archive/2009/03/19/3999986.aspx
8. json parser
    import simplejson
    result = simplejson.loads(content) //retrun dict{} or list[] accoring content,


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/94300/showart_2077933.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP