Python splitlines使用技巧

yipeiwu_com5年前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)))

相关文章

PyTorch预训练的实现

前言 最近使用PyTorch感觉妙不可言,有种当初使用Keras的快感,而且速度还不慢。各种设计直接简洁,方便研究,比tensorflow的臃肿好多了。今天让我们来谈谈PyTorch的...

Python中的匿名函数使用简介

当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(...

python判断windows系统是32位还是64位的方法

本文实例讲述了python判断windows系统是32位还是64位的方法。分享给大家供大家参考。具体分析如下: 通常64的windows系统program files文件夹(用来安装应用...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...

在PYQT5中QscrollArea(滚动条)的使用方法

在PYQT5中QscrollArea(滚动条)的使用方法

如下所示: import sys from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __in...