zoukankan      html  css  js  c++  java
  • 《Python CookBook2》 第一章 文本

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


    任务:

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

    解决方案:

    # -*- coding: UTF-8  -*-
    '''
    Created on 2014年8月29日
    path:E:Secore_pythonsrc
    @author: Administrator
    function:
    改变多行文本字符串的缩进
    '''
    def reindent(s,numSpaces):
        leading_space = numSpaces * ' ' 
        lines = [leading_space + line.strip() for line in s.splitlines(True)]
    #    return ''.join(lines)
        return '
    '.join(lines)
    
    if __name__ == "__main__":
        x='''hello
        python
             I
               love
        '''
        print reindent(x,4)
        pass
    
    
    '''
    Python中的splitlines用来分割行。当传入的参数为True时,表示保留换行符 
    。通过下面的例子就很明白了
    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! 
    
    '''

    扩展和压缩制表符    


    任务:

      将字符串中的制表符转化成一定数目的空格,或者反其道而行之。

    解决方案:

  • 相关阅读:
    [HEOI2013]Segment
    决策单调性胡扯笔记
    HDU 4352 XHXJ's LIS
    WC前计划做但一定会鸽的事情
    LGP5667 拉格朗日插值2
    BZOJ3516 国王奇遇记加强版
    ### Paper about Event Detection
    ### GIT
    ###《Max-Margin Early Event Detectors》
    ### matlab
  • 原文地址:https://www.cnblogs.com/wuzhiming/p/3944175.html
Copyright © 2011-2022 走看看