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! 
    
    '''

    扩展和压缩制表符    


    任务:

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

    解决方案:

  • 相关阅读:
    第十六章 Centos7下Docker安装GitLab
    第二十六章 Kubeadm方式搭建kubernetes高可用集群
    第二十五章 Kubernetes部署Promethus集群资源监控
    小程序遮罩层效果实现
    docker停止所有,删除容器命令
    sp欢迎页支持
    c#学习
    静态资源访问前缀
    webjar使用
    springboot静态资源配置原理
  • 原文地址:https://www.cnblogs.com/wuzhiming/p/3944175.html
Copyright © 2011-2022 走看看