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将xml文件解析成html文件的实现方法

功能就是题目所述,我的python2.7,装在windows环境,我使用的开发工具是wingide 6.0 1、首先是我设计的简单的一个xml文件,也就是用来解析的源文件 下面是这个文件...

Django 路由系统URLconf的使用

Django 路由系统URLconf的使用

URLconf是什么? URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的view函数之间的映射表;你就是以这种方式告诉Django,...

在PyCharm下打包*.py程序成.exe的方法

如下所示: 1. 在PyCharm下安装pyinstaller 2. 在Terminal下输入:“pyinstaller -F -w *.py” 就可以制作出exe。生成的文件放在同目录...

TensorFlow实现创建分类器

TensorFlow实现创建分类器

本文实例为大家分享了TensorFlow实现创建分类器的具体代码,供大家参考,具体内容如下 创建一个iris数据集的分类器。 加载样本数据集,实现一个简单的二值分类器来预测一朵花是否...

python 生成器协程运算实例

一、yield运行方式 我们定义一个如下的生成器: def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) wh...