Introduction
In this lesson, we delve into advanced string formatting in Python, focusing on f-strings and the str.format() method. Building on your existing string manipulation skills, you will learn how to craft highly formatted text using inline interpolation, number formatting, and how to choose the appropriate tool for various scenarios involving dynamic message generation.
Using f-strings for String Interpolation
F-strings, introduced in Python 3.6, offer a concise and readable way to embed expressions and variables directly in a string. The syntax involves prefixing a string with f or F and embedding expressions within curly braces {}.
name = "Alice"
age = 28
formatted_string = f"Hello, my name is {name} and I am {age} years old."
print(formatted_string)
# Output
Hello, my name is Alice and I am 28 years old.
Inline Expression Evaluation
F-strings allow for executing expressions on-the-fly, providing great flexibility.
x = 10
y = 20
calculation = f"{x} multiplied by {y} equals {x * y}."
print(calculation)
# Output
10 multiplied by 20 equals 200.
Formatting Numbers with Precision, Width, and Alignment
Both f-strings and str.format() facilitate the formatting of numbers, allowing for precision control, width specification, alignment, and use of digits' separators.
Precision and Width
value = 123.4567
formatted_value = f"{value:.2f}"
print(formatted_value)
# Output
123.46
Alignment and Fill
value = 42
formatted_value = f"|{value:<10}|{value:^10}|{value:>10}|"
print(formatted_value)
# Output
|42 | 42 | 42|
Thousands Separator
number = 1000000
formatted_number = f"{number:,}"
print(formatted_number)
# Output
1,000,000
Advanced Date and Custom Object Formatting
F-strings can also seamlessly format dates and custom objects by leveraging class methods.
Date Formatting
from datetime import datetime
now = datetime.now()
formatted_date = f"Today's date is {now:%B %d, %Y}."
print(formatted_date)
# Output
Today's date is October 29, 2023.
Custom Object Representation
For custom objects, implementing the __format__ method allows you to control how they appear in formatted strings.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __format__(self, format_spec):
return f"{self.make} - {self.model}"
car = Car("Toyota", "Corolla")
print(f"Car: {car}")
# Output
Car: Toyota - Corolla
Comparing f-strings and str.format()
Choosing the Right Approach
- F-strings are generally preferred for their readability and succinct syntax, especially when the Python version 3.6 or higher is used.
str.format()remains useful for backward compatibility in older Python versions and when formatting complex templates with repeatable patterns.
Dynamic Message Construction
Combining text, variables, and formatting options allows for the creation of dynamic and well-structured output.
items = ["apples", "bananas", "cherries"]
formatted_list = ", ".join(f"{index+1}. {item}" for index, item in enumerate(items))
message = f"Shopping list: {formatted_list}."
print(message)
# Output
Shopping list: 1. apples, 2. bananas, 3. cherries.
Summary / Key Takeaways
In this lesson, Advanced String Formatting: f-strings and format(), you have learned:
- F-strings provide a clean and modern way for inline variable and expression interpolation in Python code.
- Number formatting allows precision, alignment, and proper representation using format specifiers.
- Dates and custom objects can be formatted in readable ways using advanced string formatting techniques.
- F-strings work best in Python 3.6 and above, while
str.format()is useful for backward compatibility. - Dynamic messages and reports can be efficiently created by integrating text, variables, and sophisticated formatting options.
