Python中的splitlines用來分割行。當傳入的參數為True時,表示保留分行符號 \n。通過下面的例子就很明白了:
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 天天美味(12) - 條件判斷的縮寫
Python 天天美味(13) - struct.unpack
Python 天天美味(14) - splitlines
Python 天天美味(15) - PythonRegex操作指南(re使用)(轉)
Python 天天美味(16) - 過濾字串的技巧,map與itertools.imap
...