1.语法 : 冒号的使用
2.循环 for in
3.列表解析
---可以在一行中使用for循环将所有的值放到一个列表中:
[0, 1, 4, 9]
4.进制转换函数
hex(num) 将数字转换成十六进制数并以字符串形式返回
oct(num) 将数字转换成八进制数并以字符串形式返回
5.ASCII 转换函数
6.Template的使用 substitute严谨 safe_substitute()不严谨会原样输出
7.函数装饰器(方便操作日志等)
输出结果
---------- 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
---------------------------------------------------
小例子
>>> 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 earth
port 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,sleep
def tsfunc(func):
def wrappedFunc():
print '[%s] %s() called' % (ctime(),func.__name__)
return func()
return wrappedFunc
@tsfunc
def foo():
pass
foo()
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 os
ls = os.linesep
print "Enter file name: \n"
fname = raw_input('>')
isOk = False
# get filename
while True:
if os.path.exists(fname):
print "read "+ fname
print '-----------------------'
break
else:
isOk = True
break
if(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()