2007-06-19

 

Python Cookbook 1.14 控制多行字符串的缩进

需求:

现有一个多行字符串,要从它衍生出另一个字符串,只是要处理每行前面的空白字符,或者调整缩进.

讨论:

使用string本身提供的方法很方便的就可以实现这个需求:
 def reindent(s, numSpaces):
leading_space = numSpaces * ' '
lines = [ leading_space + line.strip( )
for line in s.splitlines( ) ]
return '\n'.join(lines)

当你处理文本的时候,可能要控制每行前的缩进,上面的方法可以控制一段字符串都使用相同的缩进.如:

>>> x = """  line one
...     line two
...  and line three
... """
>>> print x
  line one
    line two
 and line three
>>> print reindent(x, 4)
    line one
    line two
    and line three

即使原先的行缩进都不同,上面的方法都会使它们保持一致的缩进,这样虽然很方便,但有时候并不满足我们的需求:
比如我们想根据原先的缩进增加或减少空格,当然,如果是减少空格,我们需要判断原先的空格是否够减少的数字.我们用下面的代码就可以实现需要的功能:

def addSpaces(s, numAdd):
    white = " "*numAdd
    return white + white.join(s.splitlines (True))
def numSpaces(s):
    return [len(line)-len(line.lstrip( )) for line in s.splitlines( )]
def delSpaces(s, numDel):
    if numDel > min(numSpaces(s)):
        raise ValueError, "removing more spaces than there are!"
    return '\n'.join([ line[numDel:] for line in s.splitlines( ) ])

当然,上面的方法之所以可以这样简洁,都得益于str.splitlines方法,这个方法相当于split('\n').而splitlines还有一个特点,它能保留分割后行尾的换行符,如果你使用splitlines(True)就可以实现这个功能.

当然,我们也可以用上面的方法来构造更多的方法,比如:

def unIndentBlock(s):
    return delSpaces(s, min(numSpaces(s)))

相关说明:

splitlines(...)
    S.splitlines([keepends]) -> list of strings
   
    Return a list of the lines in S, breaking at line boundaries.
    Line breaks are not included in the resulting list unless keepends
    is given and true.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?