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
提交
取消
