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

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

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

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 '\n'.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 '\n'.join([line[numdel:] for line in s.splitlines()])
def unIndenBlock(s):
    return delspace(s,min(numspace(s))

转载于:https://www.cnblogs.com/hanfei-1005/p/5704187.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值