Python splitlines使用技巧
更新時間:2008年09月06日 14:09:13 作者:
Python中的splitlines用來分割行。當傳入的參數(shù)為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))
輸出結(jié)果:
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!
利用這個函數(shù),就可以非常方便寫一些段落處理的函數(shù)了,比如處理縮進等方法。如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)))
相關(guān)文章
python向xls寫入數(shù)據(jù)(包括合并,邊框,對齊,列寬)
這篇文章主要介紹了python向xls寫入數(shù)據(jù)(包括合并,邊框,對齊,列寬),幫助大家更好的利用python處理表格,感興趣的朋友可以了解下2021-02-02centos 安裝python3.6環(huán)境并配置虛擬環(huán)境的詳細教程
這篇文章主要介紹了centos-安裝python3.6環(huán)境并配置虛擬環(huán)境的詳細教程,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-02-02Python Django基礎(chǔ)二之URL路由系統(tǒng)
這篇文章主要介紹了Python Django基礎(chǔ)二之URL路由系統(tǒng) 的相關(guān)資料,需要的朋友可以參考下2019-07-07pytorch如何對image和label同時進行隨機翻轉(zhuǎn)
這篇文章主要介紹了pytorch如何對image和label同時進行隨機翻轉(zhuǎn)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09