python - 如何在 python 的类中格式化 float ?

标签 python string class floating-point formatting

我想将放入其中的数字格式化为 float ,定点数保留两位或三位小数。但是我的代码不起作用

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)

关于python - 如何在 python 的类中格式化 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223767/

相关文章:

python - 乘法追加python

ruby-on-rails - Ruby RoR 解析字符串上层

c# - ObservableCollection<string> 中的项目在绑定(bind)到 WPF 列表框时不更新

c - 查找 C 字符串中的位置

python - 关于Python中__init__的正确使用

java - 通过 EventObject 的 Getter 和 Setter - ClassCastException 同一类 (Java)

python - 使用 pathlib 时,出现错误 : TypeError: invalid file: PosixPath ('example.txt' )

带池 worker 的 Python 多进程 - 内存使用优化

python - 如何在discord.py中获取 channel 的最新消息?

c++ - C++ 中静态类函数最常见的用途是什么?