def trim(self,docstring):8 if not docstring:9 return ''10 lines = docstring.expandtabs().splitlines()11 12 indent = sys.maxint13 for line in lines[1:]:14 stripped = line.lstrip()15 print stripped16 if stripped:17 indent = min(indent, len(line) - len(stripped))18 19 trimmed = [lines[0].strip()]20 if indent < sys.maxint:21 for line in lines[1:]:22 trimmed.append(line[indent:].rstrip())23 24 while trimmed and not trimmed[-1]:25 trimmed.pop()26 while trimmed and not trimmed[0]:27 trimmed.pop(0)28 29 return '\n'.join(trimmed)
2 回答

寶慕林4294392
TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
lines = docstring.expandtabs().splitlines() |
首先,docstring是字符串(string)。
然后,string.expandtabs()是將字符串里面的tab制表符換成空格,如果沒有指定tabsize參數(shù),默認(rèn)一個(gè)tab轉(zhuǎn)化成8個(gè)空格。
(這是help里面的說明:Return a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed.)
之后,string.splitlines()是將一串字符串按行分割,并返回分割后的列表(list)。

慕萊塢森
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
事實(shí)上readlines()讀取出來(lái)的正是含有\(zhòng)n的行,而且有沒有這個(gè)換行符并不影響splitlines()的功能 In [ 1 ]: open ( 'a.txt' , 'w' ).write( "a\nb\nc\nabc" ) In [ 2 ]: !cat a.txt #ipython特有的功能,查看文本內(nèi)容 a b c abc In [ 3 ]: open ( 'a.txt' , 'r' ).readlines() Out[ 3 ]: [ 'a\n' , 'b\n' , 'c\n' , 'abc' ] In [ 4 ]: open ( 'a.txt' , 'r' ).read().splitlines() Out[ 4 ]: [ 'a' , 'b' , 'c' , 'abc' ] In [ 5 ]: for line in open ( 'a.txt' , 'r' ).read().splitlines(): ...: print line.splitlines() ...: [ 'a' ] [ 'b' ] [ 'c' ] [ 'abc' ] In [ 6 ]: for line in open ( 'a.txt' , 'r' ).readlines(): ...: print line.splitlines() ...: [ 'a' ] [ 'b' ] [ 'c' ] [ 'abc' ] |
(前面的In[x] Out[x]是ipython的輸入輸出標(biāo)識(shí)。)
添加回答
舉報(bào)
0/150
提交
取消