六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 42|回复: 0

Python 基本笔记

[复制链接]

升级  6%

15

主题

15

主题

15

主题

秀才

Rank: 2

积分
59
 楼主| 发表于 2013-1-15 02:45:32 | 显示全部楼层 |阅读模式
1.语法  : 冒号的使用
>>> pystr = "Python">>> pystr[0]#输出 'P'>>> pystr[2:5]#输出 'tho' 即[2,5) (2<=下标值<5)>>> pystr[-2]#输出 'o'>>> pystr[3:]#输出 'hon' 即下标3开始到结束>>> pystr[:2]#输出 'Py'  即[0,2)下标0开始到1结束>>> pystr[::-1]#可以当做"翻转"操作'nohtyP'>>> pystr[::2]#隔一个取一个'Pto'

2.循环 for in
>>> aDict = {'host':'earth'}>>> aDict['host']'earth'>>> aDict['port'] = 80#新增一个数据>>> aDict.keys()['host', 'port']>>> for key in aDict :print key,aDict[key]host earthport 80

3.列表解析
---可以在一行中使用for循环将所有的值放到一个列表中:
>>> squared = [x ** 2 for x in range(4)]>>> squared
[0, 1, 4, 9]
4.进制转换函数
hex(num)将数字转换成十六进制数并以字符串形式返回
oct(num)将数字转换成八进制数并以字符串形式返回

5.ASCII 转换函数
>>> ord('a')97>>> chr(97)'a'

6.Template的使用 substitute严谨 safe_substitute()不严谨会原样输出
>>> from string import Template>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')>>> print s.substitute(lang='Python',howmany=3)There are 3 Python Quotation Symbols

7.函数装饰器(方便操作日志等)
from time import ctime,sleepdef tsfunc(func):def wrappedFunc():print '[%s] %s() called' % (ctime(),func.__name__)return func()return wrappedFunc@tsfuncdef foo():passfoo()sleep(4)for i in range(2):sleep(1)foo()


输出结果
---------- python ----------
[Thu Dec 17 15:44:46 2009] foo() called
[Thu Dec 17 15:44:51 2009] foo() called
[Thu Dec 17 15:44:52 2009] foo() called
---------------------------------------------------
小例子
'writeOrRead.py'import osls = os.linesepprint "Enter file name: \n"fname = raw_input('>')isOk = False# get filenamewhile True:    if os.path.exists(fname):        print "read "+ fname        print '-----------------------'        break    else:        isOk = True        breakif(isOk):    # get file content(text) lines    all = []    print "\nEnter lines('.' by itself to quit).\n"    print "write content:"    # loop until user terminates input    while True:        entry = raw_input('>')        if entry == '.':            break        else:            all.append(entry)    # write lines to file with proper line-ending    fobj = open(fname,'w')    fobj.writelines(['%s%s' % (x,ls) for x in all])    fobj.close()    print 'DONE!'else:    # read and display text file    try:        fobj = open(fname,'r')    except IOError,e:        print fname+" file open error:",e    else:        #display contents to the screen        for eachLine in fobj:            print eachLine,        fobj.close()
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表