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


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

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

    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 '
    '.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 '
    '.join([line[numdel:] for line in s.splitlines()])
    def unIndenBlock(s):
    	return delspace(s,min(numspace(s))
    
    
  • 相关阅读:
    BZOJ3129/洛谷P3301方程(SDOI2013)容斥原理+扩展Lucas定理
    Dilworth定理
    字符串
    hash
    李超线段树(segment[HEOI2013]-洛谷T4097)
    连通数[JSOI2010]-洛谷T4306
    主席树
    splay
    树链剖分
    受欢迎的奶牛-洛谷2341
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5704187.html
Copyright © 2020-2023  润新知