Python 基本笔记
1.语法: 冒号的使用>>> pystr = "Python">>> pystr#输出 'P'>>> pystr#输出 'tho' 即#输出 'o'>>> pystr#输出 'hon' 即下标3开始到结束>>> pystr[:2]#输出 'Py'即#可以当做"翻转"操作'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,aDicthost earthport 80
3.列表解析
---可以在一行中使用for循环将所有的值放到一个列表中:
>>> squared = >>> squared
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 ----------
foo() called
foo() called
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()
页:
[1]