当前位置: 首页 > 图文教程 > 脚本技术 > Python > Python splitlines使用技巧

Python
Python 文件操作实现代码
动态创建类实例代码
python 中文字符串的处理实现代码
Python 匹配任意字符(包括换行符)的正则表达式写法
Python 开发Activex组件方法
Python+Django在windows下的开发环境配置图解
python 文件和路径操作函数小结
python 快速排序代码
Python2.5/2.6实用教程 入门基础篇
Python3 入门教程 简单但比较不错
Python 元类使用说明

Python splitlines使用技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 135 ::
收藏到网摘: n/a

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!
利用这个函数,就可以非常方便写一些段落处理的函数了,比如处理缩进等方法。如Cookbook书中的例子:
复制代码 代码如下:

def addSpaces(s, numAdd):
white = " "*numAdd
return white + white.join(s.splitlines(True))
def numSpaces(s):
return [len(line)-len(line.lstrip( )) for line in s.splitlines( )]
def delSpaces(s, numDel):
if numDel > min(numSpaces(s)):
raise ValueError, "removing more spaces than there are!"
return '\n'.join([ line[numDel:] for line in s.splitlines( ) ])
def unIndentBlock(s):
return delSpaces(s, min(numSpaces(s)))