[Numpy-discussion] floats coerced to string with "{:f}".format() ?

Robert Kern robert.kern@gmail....
Thu Jun 6 15:57:20 CDT 2013


On Thu, Jun 6, 2013 at 9:50 PM, Maccarthy, Jonathan K <jkmacc@lanl.gov> wrote:
> I'm really showing my ignorance now, I think;  so, the old-style "fmt % (tuple)" must use a different mechanism, and perhaps that's why np.savetxt never choked on a float32 for me before (yes, I am on a 64-bit system).
>
> In [8]: type(tmp.lat)
> Out[8]: numpy.float32
>
> In [9]: '%6s %8i %11.6f' % (tmp.sta, tmp.ondate, tmp.lat)
> Out[9]: '  XYZZ  2001123  -23.820000'
>
> Thanks again for your patience.

Yes, the mechanism is quite different. With %f, str.__mod__() is in
control. When it is handling the %f code, it is expecting a Python
float object *or* one that can be converted into one via float(). All
of the numpy floating and integer types can be converted to a Python
float via float().

With str.format(), the control is inverted. The value being
represented is asked via its __format__() method to handle the 'f'
format code.

--
Robert Kern


More information about the NumPy-Discussion mailing list