Python splitlines使用技巧

2022-09-28 19:21:17 字數 1240 閱讀 9436

複製** **如下:

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 izhsybphn s.splitlines( ) ])

def unindentblock(s):

return delspaces(s, min(numspac程式設計客棧es(s)))

本文標題: python splitlines使用技巧

本文位址: /jiaoben/python/44165.html

Python splitlines使用技巧

python中的splitlines用來分割行。當傳入的引數為true時,表示保留換行符 n。通過下面的例子就很明白了 mulline hello wellcome to python s world there are a lot of interesting things enjoy yours...

UIAlertController使用技巧

由於在ios8之後,蘋果將uialertview和uiactionsheet兩者進行了整合,用uialertcontroller來代替 如何建立uialertcontroller uialertcontroller alertcontroller uialertcontroller alertcon...

perl use vars pragma使用技巧

perl 中的vars是perl中的乙個pragma 預編譯指示符 專門用來預定義全域性變數,這些預定義後的全域性變數在qw 列表中,在整個引用perl檔案中皆可使用,即便使用use strict也不會報錯 複製 如下 use strict str hello world n 報錯資訊 global...