Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can anyone tell me why this NumPy record is having trouble with Python's new-style string formatting? All floats in the record choke on "{:f}".format(record).

Thanks for your help!

In [334]: type(tmp)
Out[334]: numpy.core.records.record

In [335]: tmp
Out[335]: ('XYZZ', 2001123, -23.823917388916016)

In [336]: tmp.dtype
Out[336]: dtype([('sta', '|S6'), ('ondate', '<i8'), ('lat', '<f4')])

# Some formatting works fine
In [337]: '{0.sta:6.6s} {0.ondate:8d}'.format(tmp)
Out[337]: 'XYZZ    2001123'

# Any float has trouble
In [338]: '{0.sta:6.6s} {0.ondate:8d} {0.lat:11.6f}'.format(tmp)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/jkmacc/python/pisces/<ipython-input-338-e5f6bcc4f60f> in <module>()
----> 1 '{0.sta:6.6s} {0.ondate:8d} {0.lat:11.6f}'.format(tmp)

ValueError: Unknown format code 'f' for object of type 'str'
share|improve this question

1 Answer

Maybe I am missing some catch, but it seems that you can only use {something:s}. I tried some examples and even using only float records:

tmp = (1.1, 1111, 2001123, -23.823917388916016)

tmp = numpy.array(tmp, dtype=[('test',float), ('sta',float), ('ondate,float), ('lat',float)])

the following is all right:

'{0[test]:s} {0[sta]:10s} {0[ondate]} {0[lat]:10.7s}'.format(tmp)
#'1.1 1111.0     2001123.0 -23.823   '

but this does not work:

'{0[test]:s} {0[sta]:10s} {0[ondate]} {0[lat]:10.7f}'.format(tmp)
#ValueError: Unknown format code 'f' for object of type 'str'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.