如何在Python类中格式化浮点数?

5
我想将输入的数字格式化为保留两到三位小数的浮点型和定点型数字,但是我的代码无法实现。
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''

3
你使用 format 的方式不正确:http://docs.python.org/library/string.html#formatspec - Ashwini Chaudhary
1个回答

3

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

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

7
楼主错过了 : 符号。并不需要对它们进行编号。{:2.2f} 从 Python 2.7 开始就可以使用。 - jfs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接