python 多行字符串缩进_改变多行文本字符串的缩进

改变多行文本字符串的缩进

任务:有个包含多行文本的字符串,需要创建该字符串的一个拷贝,并在每行行首添加或者删除一些空格,以保证每行的缩进都是指定数目的空格

mulLine = """Hello!!!

Wellcome to Python's world!

There are a lot of interesting things!

Enjoy yourself. Thank you!"""

print ''.join(mulLine.splitlines())

print '------------'

print ''.join(mulLine.splitlines(True))

输出结果:

Hello!!! Wellcome to Python's world! There are a lot of interesting things! Enjoy yourself. Thank you!

------------

Hello!!!

Wellcome to Python's world!

There are a lot of interesting things!

Enjoy yourself. Thank you!

字符串对象已经提供了趁手的工具,写个简单的函数即可:

>>> def reindent(s,numspace):

... leading_space=numspace*' '

... lines=[leading_space+line.strip() for line in s.splitlines()]

... return '\n'.join(lines)

...

>>> x="""

... line one

... line two

... and line three

... """

>>> print reindent(x,2)

line one

line two

and line three

一个常建的需求是调整每行行首的空格数,并确保整块文本的行之间的相对缩进不发生变化,无论是正向还是反向调整,都可以,不过反向调整需要检查一下每行行首的空格,以确保不会把非空字符截去。因此,我们需要将这个任务分解,用两个函数拉完成,再 加上一个计算每行行首空格并返回一个列表的函数,

#!/usr/bin/env python

def addSpace(s,num):

white=" "*num

return white+white.join(s.splitlines(True))

def numspaces(s):

return [(len(line)-len(line.lstrip)) for line in s.splitlines()]

def delspace(s,numdel):

if numdel>min(numspace(s)):

raise ValueError,"removing more spaces than there are"

return '\n'.join([line[numdel:] for line in s.splitlines()])

def unIndenBlock(s):

return delspace(s,min(numspace(s))


版权声明:本文为weixin_39595931原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。