Python splitlines使用技巧

yipeiwu_com6年前Python基础
复制代码 代码如下:

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)))

相关文章

python3实现elasticsearch批量更新数据

废话不多说,直接上代码! updateBody = { "query":{ "range":{ "write_date": { "g...

Python实现将绝对URL替换成相对URL的方法

本文实例讲述了Python实现将绝对URL替换成相对URL的方法。分享给大家供大家参考。具体分析如下: 一、问题: 公司一个项目需要上传图片,一开始同事将图片上传后结合当前主机拼成了一个...

Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例

Numpy matrix 必须是2维的,但是 numpy arrays (ndarrays) 可以是多维的(1D,2D,3D····ND),matrix是Array的一个小的分支,包含于...

使用Turtle画正螺旋线的方法

使用Turtle画正螺旋线的方法

import turtle as t t.setup(800,600,0,0,) t.pensize(2) t.speed(1) t.color("purple") t.shape("t...

Python对象中__del__方法起作用的条件详解

对象的__del__是对象在被gc消除回收的时候起作用的一个方法,它的执行一般也就意味着对象不能够继续引用。 示范代码如下: class Demo: def __del__(sel...