Learning Python – The format() Method for String Formatting

<span>format()</span> is a powerful tool for string formatting in Python, providing a flexible way to format strings. Below is a comprehensive introduction to the <span>format()</span> method.

1. Basic Usage

# Positional arguments
print("{} {}".format("Hello", "World"))  # Output: Hello World
# Index arguments
print("{1} {0}".format("World", "Hello"))  # Output: Hello World
# Named arguments
print("{name} is {age} years old".format(name="Alice", age=25))# Output: Alice is 25 years old

2. Numeric Formatting

# Keep two decimal places
print("{:.2f}".format(3.1415926))  # Output: 3.14
# Display with sign
print("{:+.2f}".format(3.1415926))  # Output: +3.14
print("{:+.2f}".format(-3.1415926))  # Output: -3.14
# No decimal places
print("{:.0f}".format(3.1415926))  # Output: 3
# Thousands separator
print("{:,}".format(1000000))  # Output: 1,000,000
# Percentage format
print("{:.2%}".format(0.25))  # Output: 25.00%
# Scientific notation
print("{:.2e}".format(1000000))  # Output: 1.00e+06

3. Alignment and Padding

# Right alignment, width 10
print("{:>10}".format("Hello"))  # Output:      Hello
# Left alignment, width 10
print("{:<10}".format("Hello"))  # Output: Hello     
# Center alignment, width 10
print("{:^10}".format("Hello"))  # Output:   Hello   
# Padding character
print("{:*^10}".format("Hello"))  # Output: **Hello***
print("{:0<10}".format(3.14))     # Output: 3.14000000

4. Base Conversion

# Binary
print("{:b}".format(10))  # Output: 1010
# Octal
print("{:o}".format(10))  # Output: 12
# Hexadecimal (lowercase)
print("{:x}".format(255))  # Output: ff
# Hexadecimal (uppercase)
print("{:X}".format(255))  # Output: FF

5. Special Formatting

# Accessing object attributes
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
p = Person("Bob", 30)
print("{p.name} is {p.age} years old".format(p=p))# Output: Bob is 30 years old
# Accessing list/dictionary elements
data = ["Python", "Java", "C++"]
print("{0[0]} is better than {0[1]}".format(data))# Output: Python is better than Java
info = {"name": "Alice", "age": 25}
print("{name} is {age} years old".format(**info))# Output: Alice is 25 years old

6. Advanced Usage

# Dynamic formatting
width = 10
precision = 2
value = 3.1415926
print("{:{width}.{prec}f}".format(value, width=width, prec=precision))# Output:       3.14
# Escaping curly braces
print("{{}}".format())  # Output: {}
print("{{{}}}".format("Hello"))  # Output: {Hello}

7. Comparison with % Formatting

Traditional % formatting vs format() method:

# Traditional % formatting
print("%s is %d years old" % ("Alice", 25))
# format() method
print("{} is {} years old".format("Alice", 25))

<span>format()</span> method is more powerful and flexible than % formatting, and is the officially recommended string formatting method in Python.

8. Practical Application Examples

# Table formatted output
data = [    ("Python", 3.9, 1991),    ("Java", 15, 1995),    ("C++", 20, 1985)]
for lang, ver, year in data:
    print("{:<10} | {:>5.1f} | {:>4}".format(lang, ver, year))
# Output:
# Python     |   3.9 | 1991
# Java       |  15.0 | 1995
# C++        |  20.0 | 1985
# Formatting log messages
log = "{level:^8} | {time} | {message}".format(    level="ERROR",    time="2023-05-15 14:30",    message="File not found")
print(log)# Output:  ERROR   | 2023-05-15 14:30 | File not found

<span>format()</span> method provides extremely flexible string formatting capabilities, almost meeting all common formatting needs. For Python 3.6+ versions, f-strings are a more concise option, but when dynamic formatting or compatibility with older versions is required, <span>format()</span> remains a good choice.

Leave a Comment