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

相关文章

Python读取Pickle文件信息并计算与当前时间间隔的方法分析

本文实例讲述了Python读取Pickle文件信息并计算与当前时间间隔的方法。分享给大家供大家参考,具体如下: python—–读取Pickle文件信息计算出与当前的时间间隔 生成h_d...

Pandas读取MySQL数据到DataFrame的方法

方法一: #-*- coding:utf-8 -*- from sqlalchemy import create_engine class mysql_engine(): us...

PyQt5实现暗黑风格的计时器

PyQt5实现暗黑风格的计时器

本文实例为大家分享了PyQt5实现暗黑风格的计时器的具体代码,供大家参考,具体内容如下 主要是学习多线程知识,使用的是QTime(),但是似乎用QThread()更多一些 (QThrea...

Python基础入门之seed()方法的使用

 seed() 设置生成随机数用的整数起始值。调用任何其他random模块函数之前调用这个函数。 语法 以下是seed()方法的语法: seed ( [x] ) 注意...

讲解Python中运算符使用时的优先级

讲解Python中运算符使用时的优先级

 运算符优先级来确定条件的表达式中的分组。这会影响一个表达式如何计算。某些运算符的优先级高于其他;例如,乘法运算符的优先级比加法运算更高。 例如x=7 + 3* 2;这里,x被...