Python 2.6 introduced the str.format() method with a slightly different syntax from the existing %
operator. Which is better and for what situations?
Pyt
As I discovered today, the old way of formatting strings via %
doesn't support Decimal
, Python's module for decimal fixed point and floating point arithmetic, out of the box.
Example (using Python 3.3.5):
#!/usr/bin/env python3
from decimal import *
getcontext().prec = 50
d = Decimal('3.12375239e-24') # no magic number, I rather produced it by banging my head on my keyboard
print('%.50f' % d)
print('{0:.50f}'.format(d))
Output:
0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000
There surely might be work-arounds but you still might consider using the format()
method right away.