Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Comprehensive Guide to Python's Format Specification Mini-Language

Tech May 16 1

When you call str.format(), each replacement field may contain a format specifier that tells Python exactly how to rander the corrresponding argument. The specifier is introduced by a colon : and is composed of the following optional components in order:

{[name][!conversion][:[[fill]align][sign][#][0][width][grouping][.precision][type]]}

Alignment & Width

>>> '{:<10}'.format('left')
'left      '
>>> '{:>10}'.format('right')
'     right'
>>> '{:^10}'.format('center')
'  center  '

Think of < and > as arrows pointing to the side where the content should stick.

Fill Character

Any character placed before the alignment symbol becomes the padding character.

>>> '{:*^12}'.format('Python')
'***Python***'

Numeric Options

  • + : always show sign
  • - : show sign only for negatives (default)
  • space : leading space for positives
  • # : alternate form (prefix 0b, 0o, 0x)
  • 0 : zero-padding (same as fill='0' align='=')
>>> '{:+05d}'.format(42)
'+0042'
>>> '{:#x}'.format(255)
'0xff'

Precision & Types

>>> '{:.2f}'.format(3.1415926)
'3.14'
>>> '{:.2e}'.format(123456789)
'1.23e+08'
>>> '{:,.0f}'.format(1e6)
'1,000,000'

String Truncation

For strings, .precision limits the number of characters displayed.

>>> '{:.5}'.format('全国二级计算机考试')
'全国二级计'

Multiple Representations of One Value

>>> n = 276
>>> '{0:b} {0:c} {0:d} {0:o} {0:x} {0:X}'.format(n)
'100010100 Ť 276 424 114 72'

Putting It All Together

>>> '{:0>+8.2f}'.format(-3.141)
'-0003.14'

The specifier above means:

  • 0 – use 0 as fill character
  • > – right-align
  • + – always show sign
  • 8 – total width 8 characters
  • .2f – fixed-point with 2 digits after decimal

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.