SoFunction
Updated on 2025-05-19

Detailed explanation of Python format function for advanced string formatting

1. Basic usage of format() function

1. Basic syntax

"Template String".format(parameter 1, parameter 2, ...)

2. Three basic usage methods

(1) Position parameters

print("{}of{}The results are{}".format("Zhang San", "math", 95))
# Output: Zhang San's math score is 95

(2) Index parameters

print("{0}of{2}The results are{1}".format("Zhang San", 95, "math"))
# Output: Zhang San's math score is 95

(3) Named parameters

print("{name}of{subject}The results are{score}".format(
    name="Li Si", 
    subject="English", 
    score=88
))
# Output: Li Si's English score is 88

2. Digital formatting

1. Basic number formatting syntax

"{:[Fill][Alignment][Symbol][Width][,][.Accuracy][Type]}".format(Number)

2. Commonly used digital formatting examples

Format requirements Format string Sample code Output result
Keep 2 decimal places {:.2f} "{:.2f}".format(3.14159) 3.14
Millimeter separation {:,} "{:,}".format(1234567) 1,234,567
Percentage display {:.2%} "{:.2%}".format(0.4567) 45.67%
hexadecimal {:x} "{:x}".format(255) ff
Binary {:b} "{:b}".format(10) 1010
Scientific Counting Method {:.2e} "{:.2e}".format(123456) 1.23e+05

3. Alignment and fill

Format requirements Format string Sample code Output result
Right-aligned (default) {:10} "{:10}".format(123) 123
Left aligned {:<10} "{:<10}".format(123) 123
Align center {:^10} "{:^10}".format(123) 123
Fill with 0 {:010} "{:010}".format(123) 0000000123
Fill with * {:*^10} "{:*^10}".format(123) ***123****
# Comprehensive example: Bank amount displayamount = 1234567.8912
print("Account balance: {:,.2f}Yuan".format(amount))
# Output: Account balance: RMB 1,234,567.89

3. String formatting

1. String alignment and truncation

Format requirements Format string Sample code Output result
Right aligned {:>10} "{:>10}".format("hello") hello
Left aligned {:<10} "{:<10}".format("hello") hello
Align center {:^10} "{:^10}".format("hello") hello
Truncate string {:.3} "{:.3}".format("hello") hel

2. Combining fill and alignment

# Table formatting exampledata = [("apple", 5.5, 10), ("banana", 3.2, 8), ("orange", 4.8, 15)]

for item in data:
    print("{:&lt;8} unit price: {:&gt;5.2f}Yuan in stock: {:03d}".format(*item))
    
# Output:# Apple Unit price: 5.50 yuan Inventory: 010# Banana Unit Price: 3.20 Yuan Inventory: 008# Orange Unit Price: 4.80 Yuan Inventory: 015

4. Advanced formatting skills

1. Access object properties

class Person:
    def __init__(self, name, age):
         = name
         = age

p = Person("Wang Wu", 30)
print("{}This year{}age".format(p))
# Output: Wang Wu is 30 years old this year

2. Access dictionary elements

data = {"name": "Zhao Liu", "score": 92}
print("student{name}The results are{score}".format(**data))
# Output: Student Zhao Liu's grade is 92

3. Access list elements

items = ["cell phone", "computer", "flat"]
print("product1: {0[0]}, product2: {0[1]}".format(items))
# Output: Product 1: Mobile phone, Product 2: Computer

4. Dynamic formatting

# Dynamically set the format according to the conditionsfor num in [123, 12345, 1234567]:
    print("{:{align}{width},}".format(num, align="&gt;", width=10))
    
# Output:#        123
#     12,345
#  1,234,567

5. Special formatting

1. Escape with braces

# Show the braces themselvesprint("{{}}yesformatBrackets used".format())
# Output: {} is the brackets used by format

2. Date and time formatting

from datetime import datetime
now = ()
print("{:%Y-%m-%d %H:%M:%S}".format(now))
# Output: 2023-08-15 14:30:45 (current time)

3. Custom formatting

class Temperature:
    def __init__(self, celsius):
         = celsius
    
    def __format__(self, format_spec):
        if format_spec == "f":
            return f"{ * 9/5 + 32:.1f}°F"
        return f"{:.1f}°C"

temp = Temperature(25)
print("temperature: {:f}".format(temp))  # Output: Temperature: 77.0°Fprint("temperature: {}".format(temp))    # Output: temperature: 25.0°C

6. Performance comparison

1. Comparison of various formatting methods

Format method Python version readability performance Function
%format All versions generally quick limited
() 2.6+ good middle powerful
f-string 3.6+ most Fastest powerful

2. When to use format()

✅ Suitable for scenarios:

  • Python versions 2.6 to 3.5
  • Reuse format templates required
  • Complex formatting requirements
  • Dynamic format strings are required

❌ Not suitable for scenarios:

  • Python 3.6+ Simple formatting (it is better with f-string)
  • Extremely high performance requirements scenarios

7. Practical application cases

Case 1: Generate a report

# Sales report generationsales_data = [
    ("Laptop", 12, 5999.99),
    ("Smartphone", 25, 3999.50),
    ("Tablet", 8, 2999.00)
]

# Table headerprint("{:&lt;15} {:&gt;10} {:&gt;15} {:&gt;15}".format(
    "Product Name", "Sales Quantity", "unit price", "lump sum"))
print("-" * 60)

# Table contentfor product, quantity, price in sales_data:
    total = quantity * price
    print("{:&lt;15} {:&gt;10d} {:&gt;15,.2f} {:&gt;15,.2f}".format(
        product, quantity, price, total))

# Output example:# Product Name Sales Quantity Unit Price Total Amount# ------------------------------------------------------------
# Laptop 12 5,999.99 71,999.88# Smartphone 25 3,999.50 99,987.50# Tablet 8 2,999.00 23,992.00

Case 2: Log formatting

def log_message(level, message):
    timestamp = ().strftime("%Y-%m-%d %H:%M:%S")
    print("[{:&lt;5}] {:&lt;20} {}".format(level, timestamp, message))

log_message("INFO", "System startup completed")
log_message("ERROR", "File opening failed")

# Output example:# [INFO ] 2023-08-15 14:45:30 The system startup is completed# [ERROR] 2023-08-15 14:46:12 File opening failed

8. Summary

format()Key points of the function:

1. Basic usage: Position parameters{}, index parameters{0}, named parameters{name}

2. Digital formatting:

  • Precision control:{:.2f}
  • Millimeters:{:,}
  • Alignment padding:{:0>10}

3. String formatting: Align{:<10}, cut off{:.5}

4. Advanced features:

  • Access object properties{}
  • Dynamic format{:{width}}
  • Customize__format__method

5. Special format: Date, time, brace escape

format()Provides the most powerful and flexible string formatting capabilities in Python, especially suitable for scenarios where complex format control is required. Although Python 3.6+ introduces a cleaner f-string, when multiplexing format templates or compatibility with older versions of Python,format()Still an indispensable tool.

The above is the detailed explanation of the Python format() function for advanced string formatting. For more information about Python format string formatting, please pay attention to my other related articles!