Python 基本笔记

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 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>