zoukankan      html  css  js  c++  java
  • 改变多行文本字符串的缩进

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

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

    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))
    
    
  • 相关阅读:
    easyui学习笔记1—增删改操作
    sql点滴37—mysql中的错误Data too long for column '' at row 1
    javascript获取当前url
    escape()、encodeURI()、encodeURIComponent()区别详解
    js文本框提示和自动完成
    javascript js string.Format()收集
    超链接标签为什么会造成页面颤抖
    asp.net mvc 4.0常见的几个问题
    如何使用Flashfxp上传下载文件
    点击按钮显示谷歌地图
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5704187.html
Copyright © 2011-2022 走看看