首頁  >  文章  >  後端開發  >  Python splitlines的使用技巧詳解

Python splitlines的使用技巧詳解

巴扎黑
巴扎黑原創
2017-05-21 18:50:471994瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn