String formatting: % vs. .format vs. string literal

后端 未结 16 2704
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

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

16条回答
  •  我在风中等你
    2020-11-21 05:04

    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.

提交回复
热议问题