我有分析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.'
我该如何解决这个问题?
答案 0 :(得分: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)
答案 1 :(得分:2)
您可以使用+
进行连接并返回连接字符串:
return "The largest earthquake was a "+ str(maxvalue)+ " magnitude earthquake "+ location + "."
答案 2 :(得分: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.
答案 3 :(得分:1)
使用%formatter。例如:
print "I have %d cats" % (3)
将打印"我有3只猫"。见< https://docs.python.org/2/library/string.html>