Reputation: 5911
class FormatFloat(FormatFormatStr):
def __init__(self, precision=4, scale=1.):
FormatFormatStr.__init__(self, '%%1.%df'%precision)
self.precision = precision
self.scale = scale
def toval(self, x):
if x is not None:
x = x * self.scale
return x
def fromstr(self, s):
return float(s)/self.scale
The part that confuses me is this part
FormatFormatStr.__init__(self, '%%1.%df'%precision)
does this mean that the precision gets entered twice before the 1 and once before df? Does df stand for anything that you know of? I don't see it elsewhere even in its ancestors as can be seen here:
class FormatFormatStr(FormatObj):
def __init__(self, fmt):
self.fmt = fmt
def tostr(self, x):
if x is None: return 'None'
return self.fmt%self.toval(x)
class FormatObj:
def tostr(self, x):
return self.toval(x)
def toval(self, x):
return str(x)
def fromstr(self, s):
return s
also, I put this into my Ipython and get this:
In [53]: x = FormatFloat(.234324234325435)
In [54]: x
Out[54]: <matplotlib.mlab.FormatFloat instance at 0x939d4ec>
I figured that it would reduce precision to 4 and scale to 1. But instead it gets stored somewhere in my memory. Can I retrieve it to see what it does to the number?
Thanks everyone you're very helpful!
Upvotes: 1
Views: 1374
Reputation: 4867
In ('%%1.%df' % precision)
, the first %%
yields a literal %
, %d
is substituted with precision
, and f
is inserted literally. Here's an example of how it might turn out:
>>> '%%1.%df' % 4
'%1.4f'
More about string formatting in Python
In order to use the FormatFloat
class you might try something like this:
formatter = FormatFloat(precision = 4)
print formatter.tostr(0.2345678)
Upvotes: 0
Reputation: 7918
>>> precision=4
>>> '%%1.%df'%precision
'%1.4f'
%% gets translated to %
1 is printed as is
%d prints precision as a decimal number
f is printed literally
Upvotes: 2
Reputation: 26278
In python format strings, "%%" means "insert a literal percent sign" -- the first % 'escapes' the second, in the jargon. The string in question, "%%1.%df" % precision
is using a format string to generate a format string, and the only thing that gets substituted is the "%d". Try it at the interactive prompt:
>>> print "%%1.%df" % 5
'%1.5f'
The class FormatFloat
doesn't define __repr__
, __str__
, or __unicode__
(the "magic" methods used for type coercion) so when you just print the value in an interactive console, you get the standard representation of instances. To get the string value, you would call the tostr()
method (defined on the parent class):
>>> ff = FormatFloat(.234324234325435)
>>> ff.tostr()
0.234
Upvotes: 0