当前位置: 移动技术网 > IT编程>脚本编程>Python > Python splitlines使用技巧

Python splitlines使用技巧

2019年05月25日  | 移动技术网IT编程  | 我要评论

彭南特,毛泽全,8月23日是什么节日

复制代码 代码如下:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网