Python recipe(5):Indentation
代码先行:
![div css xhtml xml Example Source Code](https://images.cnblogs.com/cnblogs_com/suyuan/quote.gif)
''' Created on 2010-5-21 @author: lk ''' #trip and add spaces def reindent(s, numofSpaces): s = s.split('\n') s = [numofSpaces * ' ' + line.lstrip() for line in s] s = '\n'.join(s) return s #do not trip def addSpaces(s, numAdd): white = ' ' * numAdd return white + white.join(s.splitlines(1)) def delSpaces(s, numDel): def aux(line, numDel=numDel, white=' ' * numDel): if line[:numDel] != white: raise ValueError, 'removing more spaces than there are!' return line[numDel:] return ''.join(map(aux, s.splitlines(1))) def numOfSpaces(s): return [len(line)-len(line.lstrip()) for line in s.splitlines(1)] def unIndentBlock(s): return delSpaces(s, min(numOfSpaces(s))) if __name__ == '__main__': s = ' ' * 5 + "Hello \n" + ' ' * 7 + "World" print reindent(s, 5) print reindent(s, 10) print addSpaces(s, 2) print delSpaces(s, 2) print numOfSpaces(s) print unIndentBlock(s)
以上代码改写自Python Cookbook 3-12
概述:
对多行字符块进行缩进。其中reindent函数首先左对齐(删除空白),然后添加相应数量空白符;addSpaces不删除每行开头原有的空白符;delSpaces函数去除每行相应数目的空白符;numOfSpaces计算每行开头的空白符数
代码说明:
1. string对象的splitlines函数,依照换行符分割字符串,若参数为True则保留换行符,默认False。和string对象的split(‘\n’)等价