如何在python中设置类内浮点的格式?

如何在python中设置类内浮点的格式?,python,string,class,floating-point,formatting,Python,String,Class,Floating Point,Formatting,我想把放在这里的数字格式化为浮点数,固定点数,小数点后两位或三位。但是,我的代码不起作用 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

我想把放在这里的数字格式化为浮点数,固定点数,小数点后两位或三位。但是,我的代码不起作用

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)
这将生成错误消息:

'AttributeError: 'float' object has no attribute '2f''

您需要对格式代码进行编号。此外,如果在使用新格式代码时确实要打印
{
,则必须使用双
{
来转义格式:

"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)

您使用的
格式不正确:OP missed
。不需要对它们进行“编号”。
{:2.2f}
自Python 2.7以来一直有效。