《Python CookBook2》 第一章 文本 - 改变多行文本字符串的缩进 && 扩展和压缩制表符(此节内容待定)

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


任务:

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

 

解决方案:

 

# -*- coding: UTF-8  -*-
'''
Created on 2014年8月29日
path:E:\Se\core_python\src\
@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 '\n'.join(lines)

if __name__ == "__main__":
    x='''hello
    python
         I
           love
    '''
    print reindent(x,4)
    pass


'''
Python中的splitlines用来分割行。当传入的参数为True时,表示保留换行符 \n。通过下面的例子就很明白了
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! 

'''

 

 

 

 

 

扩展和压缩制表符    


 

任务:

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

 

解决方案:

 

posted @ 2014-08-29 23:11  道生一_三生万物  阅读(302)  评论(0编辑  收藏  举报
returnTop $(function(){ $('#returnTop').click(function () { $('html,body').animate({ scrollTop: '0px' }, 800); returnfalse; }); });