2013-04-25 30 views
1

我想格式化爲浮點數的數字,固定點數字爲兩位或三位小數。但是我的代碼不能正常工作如何在Python中的類中設置浮點數?

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 – 2013-04-25 20:07:47

回答

1

你需要編號的格式代碼。另外,如果你真的想使用新的格式代碼時打印{,你必須使用一個雙{{逃離格式:

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

OP錯過了':'。沒有必要「給它們編號」。自Python 2.7以來,'{:2.2f}'起作用。 – jfs 2013-04-26 12:36:24

相關問題