请问python expandtabs().splitlines(),到底是为了做什么?

def trim(self,docstring):
8 if not docstring:
9 return ''
10 lines = docstring.expandtabs().splitlines()
11 
12 indent = sys.maxint
13 for line in lines[1:]:
14 stripped = line.lstrip()
15 print stripped
16 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)

catspeake
浏览 101回答 2
2回答

宝慕林4294392

lines&nbsp;=&nbsp;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)。

慕莱坞森

事实上readlines()读取出来的正是含有\n的行,而且有没有这个换行符并不影响splitlines()的功能&nbsp;In&nbsp;[1]:&nbsp;open('a.txt','w').write("a\nb\nc\nabc")&nbsp;In&nbsp;[2]:&nbsp;!cat&nbsp;a.txt&nbsp;#ipython特有的功能,查看文本内容abcabcIn&nbsp;[3]:&nbsp;open('a.txt','r').readlines()Out[3]:&nbsp;['a\n',&nbsp;'b\n',&nbsp;'c\n',&nbsp;'abc']&nbsp;In&nbsp;[4]:&nbsp;open('a.txt','r').read().splitlines()Out[4]:&nbsp;['a',&nbsp;'b',&nbsp;'c',&nbsp;'abc']&nbsp;In&nbsp;[5]:&nbsp;for&nbsp;line&nbsp;in&nbsp;open('a.txt','r').read().splitlines():&nbsp;&nbsp;&nbsp;...:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print&nbsp;line.splitlines()&nbsp;&nbsp;&nbsp;...:['a']['b']['c']['abc']&nbsp;In&nbsp;[6]:&nbsp;for&nbsp;line&nbsp;in&nbsp;open('a.txt','r').readlines():&nbsp;&nbsp;&nbsp;...:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print&nbsp;line.splitlines()&nbsp;&nbsp;&nbsp;...:['a']['b']['c']['abc'](前面的In[x] Out[x]是ipython的输入输出标识。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python