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 splitlines的使用技巧詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!