Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format floating points within a class in python?

I want to format numbers that are put into this as float, fixed point numbers to two or three decimal places. However my code does not work

class Quake:
    """Earthquake in terms of latitude, longitude, depth and magnitude"""

    def __init__(self, lat, lon, depth, mag):
        self.lat=lat
        self.lon=lon
        self.depth=depth
        self.mag=mag

    def __str__(self):
        return "M{2.2f}, {3.2f} km, lat {3.3f}\N{DEGREE\
         SIGN lon {3.3f}\N{DEGREE SIGN}".format(
            self.mag, self.depth, self.lat, self.lon)

This produces the error message:

'AttributeError: 'float' object has no attribute '2f''
like image 715
Imog Avatar asked Oct 22 '22 11:10

Imog


1 Answers

You need to number the format codes. Also, if you really want to print { when using the new format code, you have to use a double {{ to escape the format:

"M{0:2.2f}, {1:3.2f} km, lat {2:3.3f}N{{DEGREE SIGN}} lon {3:3.3f}\N{{DEGREE SIGN}}".format(
self.mag, self.depth, self.lat, self.lon)
like image 142
tiago Avatar answered Oct 31 '22 17:10

tiago