2015-09-19 34 views
0

任何人都可以解釋爲什麼我無法做到這一點,如果有任何workaroud?無法寫入函數返回到文件

這適用於前。

a, b, c, d = extract(text) 

fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(a, b, c, d)) 

但這並不

fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(extract(text))) 
+1

什麼是'extract'功能? – hjpotter92

+1

把'。.format(extract(text)))'改成'... .format(* extract(text)))' – alfasin

回答

0

如果extract()返回一個元組,你需要將它傳遞給格式之前解包的返回值:

星號在這裏所做的伎倆。

說明:在Python,string#format具有以下特徵:

.format(*args, **keyword_args) 

***被稱爲解包運算符(在紅寶石,它們被稱爲提示圖標)。它們的唯一目的是分別將列表(元組,數組)和字典(字典,對象)轉換爲參數列表。

extract()返回一個列表,但格式需要一個參數列表。所以之前,你必須:

#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar'] 
.format(extract(text)) # this thing 
.format(('foo', 'bar')) # is equivalent to this, note the parentheses 

在這種情況下,元組(「富」,「棒」)等於第一格式令牌{0}和格式不知道做什麼用的元組做記號(我應該使用哪個元組元素?)。

當您使用擴展運算符,您要變換的extract()輸出入功能期待的列表,因此:

#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar'] 
.format(*extract(text)) # this thing 
.format('foo', 'bar') # is equivalent to this 
+0

你說的對,我忘了提及我返回4個參數。如果你想請解釋我暗示 – Maxitj

+0

我編輯我的答案來解釋它:) – fixmycode