2014-04-01 25 views
1

我有分析csv文件的代碼,並返回列的最大值和與maxvalue相同行中的另一列的值。我在格式化輸出時遇到問題。返回一個字符串,如何格式化輸出

代碼:

import csv 

def bigQuake(inputfilename): 
    with open(inputfilename,"r") as input_file: 
     reader = csv.reader(input_file) 

     maxvalue = 0.0 
     location = None 
     for line in reader: 
      try: 
       p = float(line[4]) 
       if p > maxvalue: 
        maxvalue = p 
        location = line[13] 
      except ValueError: 
       pass 
    return "The largest earthquake was a", maxvalue, "magnitude earthquake", location + "." 

電流輸出看起來像什麼:

>>> bigQuake("file.csv") 
>>> ('The largest earthquake was a', 6.3, 'magnitude earthquake', '13km N of Kunisaki-shi, Japan.') 

我想要什麼:

>>> bigQuake("file.csv") 
>>> 'The largest earthquake was a 6.3 magnitude earthquake 13km N of Kunisaki-shi, Japan.' 

我該如何解決這個問題?

回答

5

使用此,

return "The largest earthquake was a" + str(maxvalue) + "magnitude earthquake" + location + "." 

OR

return "The largest earthquake was a %s magnitude earthquake %s." % (maxvalue, location) 
+0

第二個解決方案會更好,因爲它會忽略一些意想不到的錯誤。 –

+0

什麼樣的錯誤? – AspirationZ

+0

@AspirationZ請參閱此鏈接https://docs.python.org/2/library/stdtypes.html#string-formatting – dhana

2

可以使用+進行連結,並返回連接字符串:

return "The largest earthquake was a "+ str(maxvalue)+ " magnitude earthquake "+ location + "." 
2

使用format

>>> maxvalue=6.3 
>>> location='13km N of Kunisaki-shi, Japan' 
>>> 
>>> template="The largest earthquake was a {} magnitude earthquake, {}." 
>>> 
>>> template.format(maxvalue, location) 
'The largest earthquake was a 6.3 magnitude earthquake, 13km N of Kunisaki-shi, Japan.' 

然後如果你想以適應文本到指定的寬度,使用textwrap

>>> import text wrap 
>>> print '\n'.join(textwrap.wrap(template.format(maxvalue, location), 30)) 
The largest earthquake was a 
6.3 magnitude earthquake, 13km 
N of Kunisaki-shi, Japan.