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

Python
wxPython 入门教程
Python日期操作学习笔记
Python函数学习笔记
Python转码问题的解决方法
python sqlobject(mysql)中文乱码解决方法
Python 连连看连接算法
Python类的基础入门知识
Python GAE、Django导出Excel的方法
python 参数列表中的self 显式不等于冗余
下载糗事百科的内容_python版
pymssql ntext字段调用问题解决方法
Python 面向对象 成员的访问约束
python 测试实现方法
python 数据加密代码
python zip文件 压缩
python 文件与目录操作
python3.0 字典key排序
Python 学习笔记
Python Mysql数据库操作 Perl操作Mysql数据库
Python MD5文件生成码

Python splitlines使用技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 139 ::
收藏到网摘: 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)))