AspirationZ
AspirationZ

Reputation: 39

Return a string, how to format output

I have code that analyzes a csv file and returns the max value of a column and the value of another column in the same row as maxvalue. I'm having trouble formatting the output.

Code:

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 + "."

What a current output looks like:

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

What I want:

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

How do I fix this?

Upvotes: 1

Views: 178

Answers (4)

dawg
dawg

Reputation: 104102

Use 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.'

Then if you want to fit that text into a specified width, use 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.

Upvotes: 2

cheshircat
cheshircat

Reputation: 183

Use the % formatter. For instance:

print "I have %d cats" % (3)

will print "I have 3 cats". See < https://docs.python.org/2/library/string.html>.

Upvotes: 1

venpa
venpa

Reputation: 4318

You can use + for concatenation and return concatenated string:

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

Upvotes: 2

dhana
dhana

Reputation: 6525

Use this,

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

OR

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

Upvotes: 5

Related Questions