Python splitlines使用技巧
更新時(shí)間:2008年09月06日 14:09:13 作者:
Python中的splitlines用來分割行。當(dāng)傳入的參數(shù)為True時(shí),表示保留換行符 \n。通過下面的例子就很明白了
復(fù)制代碼 代碼如下:
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!
利用這個(gè)函數(shù),就可以非常方便寫一些段落處理的函數(shù)了,比如處理縮進(jìn)等方法。如Cookbook書中的例子:
復(fù)制代碼 代碼如下:
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 tkinter實(shí)現(xiàn)日期選擇器
這篇文章主要為大家詳細(xì)介紹了Python tkinter實(shí)現(xiàn)日期選擇器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02python向xls寫入數(shù)據(jù)(包括合并,邊框,對(duì)齊,列寬)
這篇文章主要介紹了python向xls寫入數(shù)據(jù)(包括合并,邊框,對(duì)齊,列寬),幫助大家更好的利用python處理表格,感興趣的朋友可以了解下2021-02-02Python計(jì)算公交發(fā)車時(shí)間的完整代碼
這篇文章主要介紹了Python計(jì)算公交發(fā)車時(shí)間的完整代碼,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02centos 安裝python3.6環(huán)境并配置虛擬環(huán)境的詳細(xì)教程
這篇文章主要介紹了centos-安裝python3.6環(huán)境并配置虛擬環(huán)境的詳細(xì)教程,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-02-02Python Django基礎(chǔ)二之URL路由系統(tǒng)
這篇文章主要介紹了Python Django基礎(chǔ)二之URL路由系統(tǒng) 的相關(guān)資料,需要的朋友可以參考下2019-07-07對(duì)pandas處理json數(shù)據(jù)的方法詳解
今天小編就為大家分享一篇對(duì)pandas處理json數(shù)據(jù)的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-02-02pytorch如何對(duì)image和label同時(shí)進(jìn)行隨機(jī)翻轉(zhuǎn)
這篇文章主要介紹了pytorch如何對(duì)image和label同時(shí)進(jìn)行隨機(jī)翻轉(zhuǎn)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09