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

Python
python 正则式使用心得
python 正则式 概述及常用字符
用python分割TXT文件成4K的TXT文件
python getopt 参数处理小示例
python 运算符 供重载参考
python 查找文件夹下所有文件 实现代码
打印出python 当前全局变量和入口参数的所有属性
python 解析html之BeautifulSoup
python self,cls,decorator的理解
python 自动提交和抓取网页
python 域名分析工具实现代码
Python 文件重命名工具代码
python 提取文件的小程序
Python 网络编程说明
python 简易计算器程序,代码就几行
python encode和decode的妙用
Python开发编码规范
学习python (1)
学习python (2)
简明 Python 基础学习教程

Python splitlines使用技巧


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