2013年10月25日

Python Cookbook学习记录 ch1_17_2013/10/25

摘要: 1.16替换字符串中的字串给定一个字符串,通过查询一个替换字典,将字典中被标记的子字符串替换掉>>> new_style = string.Template('this is $fst and this is $snd')>>> print new_style.substitute(fst=5,snd=10)this is 5 and this is 10>>> print new_style.substitute({'fst':5,'snd':10})this is 5 and this i 阅读全文

posted @ 2013-10-25 21:34 七海之风 阅读(170) 评论(0) 推荐(0)

Python Cookbook学习记录 ch1_15_2013/10/25

摘要: 1.15扩展和压缩制表符tab和空格的互转,一般是tab转空格,一个expandtabs()就足够了,空格转tab可能只出在考试题中s = "a\t aaaaa\t aaaa" s1 = s.expandtabs() print s,len(s) print s1,len(s1) #把空格转成tab def unexpand(s,tablen = 8): import re #切分成空格和非空格 pieces = re.split(r'( +)',s.expandtabs()) #记录当前字符串总长度 len... 阅读全文

posted @ 2013-10-25 21:08 七海之风 阅读(125) 评论(0) 推荐(0)

Python Cookbook学习记录 ch1_14_2013/10/25

摘要: 1.14 改变多行文本字符串的缩进>>> def reindent(s,spacenum): leadspace = ' '*spacenum lines = [leadspace+line.strip() for line in s.splitlines()] return '\n'.join(lines)确保文本每一行直接的相对缩进,这样子需要提前计算每一行行首的空格数(下述代码没有按照书中的方式进行处理)>>> def numspaces(s): return [len(line)-len(line.lstrip()) 阅读全文

posted @ 2013-10-25 20:59 七海之风 阅读(158) 评论(0) 推荐(0)

导航