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貢獻2021條經驗 獲得超8個贊
lines = docstring.expandtabs().splitlines() |
首先,docstring是字符串(string)。
然后,string.expandtabs()是將字符串里面的tab制表符換成空格,如果沒有指定tabsize參數,默認一個tab轉化成8個空格。
(這是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貢獻1810條經驗 獲得超4個贊
事實上readlines()讀取出來的正是含有\n的行,而且有沒有這個換行符并不影響splitlines()的功能 In [1]: open('a.txt','w').write("a\nb\nc\nabc") In [2]: !cat a.txt #ipython特有的功能,查看文本內容abcabcIn [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的輸入輸出標識。)
添加回答
舉報
0/150
提交
取消
