亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問python expandtabs().splitlines(),到底是為了做什么?

請問python expandtabs().splitlines(),到底是為了做什么?

catspeake 2022-11-18 18:14:40
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)。


查看完整回答
反對 回復 2022-11-22
?
慕萊塢森

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的輸入輸出標識。)


查看完整回答
反對 回復 2022-11-22
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號