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中SocketServer模块处理网络请求的用法

SocketServer创建一个网络服务框架。它定义了类来处理TCP,UDP, UNIX streams 和UNIX datagrams上的同步网络请求。 一、Server Types...

Python实现代码统计工具

本文实例为大家分享了Python实现代码统计工具的具体代码,供大家参考,具体内容如下 思路:首先获取所有文件,然后统计每个文件中代码的行数,最后将行数相加. 实现的功能: 统计每个文件的...

Python3.4 tkinter,PIL图片转换

Python3.4 tkinter,PIL图片转换

先给大家分享一下全部代码 import os from PIL import Image import tkinter import tkinter.filedialog impor...

浅谈Python2.6和Python3.0中八进制数字表示的区别

在Python2.x中表示八进制的方式有两种:以'0'开头和以'0o'(字母o)开头:   Python2.7中: >>> 0100 64 >>&g...

Django项目中用JS实现加载子页面并传值的方法

在Django的开发过程中,有一些功能是通过JS根据用户的不同选择来加载页面中的某一部分(子页面)的。如果子页面中有我们需要传入的值。可以这么实现 在js函数中调用 $("#bas...