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实现的直接插入排序算法示例

Python实现的直接插入排序算法示例

本文实例讲述了Python实现的直接插入排序算法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- '''直接插入的python实现 时间复杂度O(...

python单线程文件传输的实例(C/S)

python单线程文件传输的实例(C/S)

客户端代码: #-*-encoding:utf-8-*- import socket import os import sys import math import time...

Python获取当前页面内所有链接的四种方法对比分析

本文实例讲述了Python获取当前页面内所有链接的四种方法。分享给大家供大家参考,具体如下: ''' 得到当前页面所有连接 ''' import requests import re...

python使用turtle库与random库绘制雪花

python使用turtle库与random库绘制雪花

本文实例为大家分享了python绘制雪花的具体代码,供大家参考,具体内容如下 代码非常容易理解,画着玩玩还是可以的。直接上代码 # -*- coding: utf-8 -*- """...

pytorch 把MNIST数据集转换成图片和txt的方法

本文介绍了pytorch 把MNIST数据集转换成图片和txt的方法,分享给大家,具体如下: 1.下载Mnist 数据集 import os # third-party librar...