Command Palette

Search for a command to run...

AI Programming

String Formatting

Basic Concepts and Width Control

String formatting controls data display in Python programs. Imagine arranging data in a neat table where each column has consistent width. Python provides format() method and f-strings to control output display.

The basic replacement field syntax is {name : width}, where name determines the argument and width sets the minimum output width. When width is smaller than the original string length, Python still displays the complete string.

Format Types for Number Systems

Format TypeSymbolExample InputOutputUsage
Decimald4545Default for integer
Binaryb45101101Bit representation
Octalo4555Unix systems
Hexadecimalx/X452d/2DLow-level programming
Pythonwidth_and_types.py
# Width control with various formatsprint('|{0:15}|'.format('xxx'))     # Output: |xxx            |print('a = {0:6d}'.format(45))      # Output: a =     45print('a = {0:10b}'.format(45))     # Output: a =     101101print('a = {0:6x}'.format(45))      # Output: a =     2d# Width smaller than string - not truncatedprint('|{0:1}|'.format('xxx'))      # Output: |xxx|

Position Settings and Fill Characters

Alignment Options

Mermaidmermaid
Loading
SymbolNameBehaviorDefault for
<LeftText on left, padding on rightString, objects
>RightText on right, padding on leftNumbers
^CenterText in center, even padding-

Fill Characters and Advanced Formatting

Fill character determines the character to fill empty space. Default uses space, but can be replaced with any character except { and }.

Pythonalignment_fill.py
# Basic alignmentprint('|{0:<15}|'.format('xxx'))    # Output: |xxx            |print('|{0:>15}|'.format('xxx'))    # Output: |            xxx|print('|{0:^15}|'.format('xxx'))    # Output: |      xxx      |# Custom fill charactersprint('|{0:-<15}|'.format('xxx'))   # Output: |xxx------------|print('|{0:*>15}|'.format('xxx'))   # Output: |************xxx|print('|{0:^^15}|'.format('xxx'))   # Output: |^^^^^^xxx^^^^^^|# Decimal formattingx = 123.98print('x = {0:12f}'.format(x))      # Output: x =   123.980000print('x = {0:12e}'.format(x))      # Output: x = 1.239800e+02

Argument Reference Methods

Python provides three ways to reference arguments in replacement fields, each with different rules.

Mermaidmermaid
Loading

Reference Method Comparison

MethodSyntaxAdvantagesLimitations
Numbered{0}, {1}Explicit control, can repeatMust match argument count
Keyword{name}, {age}Easy to read, flexibleNames must match
Automatic{}, {}Simple syntaxCannot mix with numbered
Pythonargument_methods.py
# Numbered fields - explicit controlprint('{2} - {0} - {1}'.format('first', 'second', 'third'))# Output: third - first - second# Keyword fields - using namesprint('{name} is {age} years old'.format(name='Alice', age=25))# Output: Alice is 25 years old# Automatic numbering - sequential orderprint('{} + {} = {}'.format(5, 3, 8))# Output: 5 + 3 = 8# Error handlingtry:  print('{a} - {b}'.format(a='xxx'))  # Will errorexcept KeyError as e:  print(f"KeyError: {e}")  # Output: KeyError: 'b'  try:  print('{0} - {1}'.format('xxx'))    # Will errorexcept IndexError as e:  print(f"IndexError: {e}")  # Output: IndexError: Replacement index 1 out of range for positional args tuple

Precision Control and Sign Specification

Precision for Decimal Numbers

Precision controls the number of decimal places or significant digits in number display.

Format TypePrecision BehaviorExample
f/FDecimal places{:.2f}123.99
e/EDecimal places in exponential{:.2e}1.24e+02
g/GSignificant digits{:.3g}124

Sign Options

Mermaidmermaid
Loading
SymbolBehaviorExample
+Always show sign+100, -200
-Only negative sign (default)100, -200
(space)Space for positive 100, -200
Pythonprecision_sign.py
# Precision controlprint('x = {0:.3f}'.format(123.98765))     # Output: x = 123.988print('x = {0:12.2e}'.format(1.987e-10))   # Output: x =     1.99e-10print('x = {0:.3g}'.format(1.123456))      # Output: x = 1.12# Sign specificationnumbers = [-100, 200, -300]print('Default:', ['{:d}'.format(n) for n in numbers])# Output: Default: ['-100', '200', '-300']print('Always sign:', ['{:+d}'.format(n) for n in numbers])# Output: Always sign: ['-100', '+200', '-300']print('Space positive:', ['{: d}'.format(n) for n in numbers])# Output: Space positive: ['-100', ' 200', '-300']# Rounding behaviorprint('Tiny number f: {0:12f}'.format(1.1e-10))  # Output: Tiny number f:     0.000000print('Tiny number g: {0:12g}'.format(1.1e-10))  # Output: Tiny number g:      1.1e-10

F-Strings and Dynamic Templates

F-Strings (Python 3.6+)

F-strings provide the simplest syntax with direct expression evaluation. Faster and more readable compared to format().

Dynamic Format Templates

Format templates can use variables for specification, useful when format is determined dynamically.

Pythonfstrings_dynamic.py
# F-strings - simple syntaxname, age = 'Alice', 25print(f'{name} is {age} years old')           # Output: Alice is 25 years oldprint(f'Next year: {name} will be {age + 1}') # Output: Next year: Alice will be 26# Dynamic format templatesvalue, width, fill, align = 'data', 12, '-', '^'template = '|{val:{f}{a}{w}}|'result = template.format(val=value, w=width, f=fill, a=align)print(result)                                 # Output: |----data----|# Comparison - same output, different methodsx = 123.456print('Old style: %8.2f' % x)                # Output: Old style:   123.46print('Format method: {0:8.2f}'.format(x))   # Output: Format method:   123.46print(f'F-string: {x:8.2f}')                 # Output: F-string:   123.46# Complex f-string with format specimport mathradius = 5.7print(f'Area: {math.pi * radius**2:.2f} cm²') # Output: Area: 102.07 cm²

Complete Format Specification Pattern

Mermaidmermaid
Loading

Format specification follows the pattern {name:fill align sign width .prec type} where each component is optional and has a specific function to control output display.