创建一个没有引号的新循环

时间:2015-06-15 09:59:00

标签: python string for-loop

我在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

我想得到任何帮助。

2 个答案:

答案 0 :(得分:2)

您的itemtuple

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

元组的str版本是其repr代表,例如:

>>> 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的文档。

答案 1 :(得分:-1)

您必须像item一样加入item = ' '.join(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()