`

dive into python 笔记

 
阅读更多

第三章

tuple 是没有append, remove, index方法的

格式化字符串: "Count: %s" % (sCount, )     最后的逗号必不可少

dictionary 的方法:keys(), values(), items()

 

第四章

内置函数:

type()  返回数据类型

str()    转化为字符串

dir()    返回任意对象的属性和方法列表

callable()    收集任何对象为参数,如果对象是可调用的,则True

getattr()    得到函数的引用。getattr(li, "append")

过滤列表: [ mapping-exp   for    element   in   source-list    if   filter-exp ]   eg: [ elem for elem in li if len(elem) > 1 ]

lambda函数介绍:

 

>>> g = lambda x: x*2
>>> g(3)
6

 

processFunc = collapse and ( lambda s: " ".join(s.plit())) or (lambda s : s)

 

 

第六章 异常和文件处理

try:
 fsock = open("/notthere")
except IOError:
 print "file does not exist"

 

os.listdir(path)    显示路径的所有目录和文件

os.path.isfile()

os.path.isdir()

os.getcwd()

os.path.splitext(str)

os.path.join()

glob.glob(str)    可适用于通配符的目录和文件 

 

第七章 正则表达式

re.sub('ROAD$', 'RD.', s)

^  表示仅在字符串开始匹配其后的字符串内容

$  表示限制只在字符串的末尾匹配

re.search(pattern,  str)     

pattern:    M{0,3}    匹配M 0-3次

?   匹配0或1次

+   匹配1或多次

*    匹配0或多次

松散正则表达式:

>>> pattern = """
^ # beginning of string M{0,3} # thousands - 0 to 3 M's
(CM|CD|D?C{0,3}) #
(XC|XL|L?X{0,3}) #
(IX|IV|V?I{0,3}) #
# hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), or 500-800 (D, followed by 0 to 3 C's)
# tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), or 50-80 (L, followed by 0 to 3 X's)
# ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), or 5-8 (V, followed by 0 to 3 I's)
$ # end of string
"""
>>> re.search(pattern, 'M', re.VERBOSE)   #re.VERBOSE 标志这是松散正则

 

>>> phonePattern = re.compile(r'^(\d{3})-(\d{3})-(\d{4})$')
>>> phonePattern.search('800-555-1212').groups()

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics