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使用str & repr转换字符串

可能比较 low 还是记录一下: str 和 repr的使用过程 str 是一个类型 (int, long 类似), 同样她也可以作为一个工厂方法 实例一个 string re...

python实现简单成绩录入系统

学了一个多月的python,做了一个小程序:python实现简单成绩录入系统,实验一下 menu部分 from tkinter import*#这是一个python模块,python...

python字典基本操作实例分析

本文实例讲述了python字典基本操作。分享给大家供大家参考。具体如下: d2 = {'spam': 2, 'ham': 1, 'eggs': 3} # make a diction...

Python3如何对urllib和urllib2进行重构

这篇文章主要介绍了Python3如何对urllib和urllib2进行重构,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python...

Python中is和==的区别详解

Python中有很多运算符,今天我们就来讲讲is和==两种运算符在应用上的本质区别是什么。 在讲is和==这两种运算符区别之前,首先要知道Python中对象包含的三个基本要素,分别是:i...