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

相关文章

python使用正则表达式(Regular Expression)方法超详细

python使用正则表达式(Regular Expression)方法超详细

一、导入re库 python使用正则表达式要导入re库。 import re 在re库中。正则表达式通常被用来检索查找、替换那些符合某个模式(规则)的文本。 二、使用正则表达式步...

python里将list中元素依次向前移动一位

问题 定义一个int型的一维数组,包含10个元素,分别赋值为1~10, 然后将数组中的元素都向前移一个位置, 即,a[0]=a[1],a[1]=a[2],…最后一个元素的值是原来第一个元...

使用python将图片按标签分入不同文件夹的方法

使用python将图片按标签分入不同文件夹的方法

给定图像集如下,所有类别的图片均在一个文件夹内: 给定与图片名相匹配的表格,声明每张图片对应的类别(共有20个类别): 那么,如何根据表格中所给的类别将图片分入对应的文件夹内呢?以我...

python flask 如何修改默认端口号的方法步骤

场景:按照github文档上启动一个flask的app,默认是用5000端口,如果5000端口被占用,启动失败。 样例代码: from flask import Flask...

浅谈Python3 numpy.ptp()最大值与最小值的差

numpy.ptp() 是计算最大值与最小值差的函数,用法如下: import numpy as np a = np.array([np.random.randint(0, 20,...