2015-06-15 12 views
0

我在python上寫了一個函數,它應該打印下面的句子。創建一個不帶引號的新循環

def write_to_file(matrix, path): 
    f = open(path, "w") 
    f.write('\r\n') 
    for i in range (2,5): 
     item = (bestQuarterRate(matrix, i)) 
     item = (str(item)) 
     print item 
     f.write(item) 
    f.close() 

的問題是,我得到這個:

('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666) 
('Highest quarter average exchange change is between', '1/4/15', 'and', '1/6/15', 'with rate:', 598.1673333333333) 
('Highest quarter volume is between', '1/4/13', 'and', '1/6/13', 'with rate:', 158.7078934137758) 

,我需要把它改成這樣:

Highest quarter rate is between 1/1/15 and 1/3/15 with rate: 924.996666667 

Highest quarter average exchange is between 1/10/14 and 1/12/14 with rate: 1503.67333333 

Highest quarter volume change rate is between 1/4/13 and 1/6/13 with rate: 158.707893414 

The best year is 2014 with an average exchange value of: $1601932.83452 

我希望得到任何幫助。

+4

明顯'bestQuarterRate'返回一個**元組** - 如果你想使它成爲一個單獨的字符串,你可以使用例如('item')。 – jonrsharpe

回答

2

itemtuple

>>> item = ('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666) 

元組的str荷蘭國際集團的版本是其repr esentation,例如:

>>> str(item) 
"('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666)" 

相反,你想轉換每個元素耳鼻喉科的元組爲一個字符串,然後再加入所有這些字符串連成一個字符串:

>>> ' '.join(map(str, item)) 
'Highest quarter rate is between 1/1/15 and 1/3/15 with rate: 924.996666667' 

爲進一步說明,請參閱mapstrstr.join的文檔。

+0

作品令人驚歎。非常感謝 – Dana

-1

您必須像item = ' '.join(item)一樣加入item元組。

全碼:

def write_to_file(matrix, path): 
    f = open(path, "w") 
    f.write('\r\n') 
    for i in range (2,5): 
     item = (bestQuarterRate(matrix, i)) 
     print item 
     item = ' '.join(item) 
     f.write(item) 
    f.close() 
+1

這將無法正常工作,因爲您已將'item'首先轉換爲字符串,因此您將得到例如''''''最高四分之一','1/1/1 5','和','1/3/1 5','withrate:',9 2 4。9 9 6 6 6 6 6 6 6 6 6 6 6)「'...... – jonrsharpe

+0

true。行不通。 – Dana

+0

我沒有注意到在原代碼中。好的趕上!修正它:) – ssundarraj