Blog Post #115: f-Strings Revisited: Advanced Formatting Techniques

In Post #18, we introduced f-strings as the modern, Pythonic way to embed variables into strings. We learned that a simple {variable} is a huge improvement over manual concatenation with the + operator. However, the power of f-strings goes far beyond simple variable insertion.

In this post, we’ll explore the format specifier, a mini-language inside f-strings that gives you precise control over how your values are displayed. We’ll cover decimal precision, number padding, and date formatting.

The Format Specifier Mini-Language

The magic of advanced f-string formatting happens after a colon : inside the curly braces.

The general syntax looks like this: f"{value:format_specifier}"

The format_specifier is a short code that tells Python how you want the value to be presented in the final string.

Formatting Numbers

Controlling Decimal Precision

This is one of the most common use cases. When working with floats, you often want to control the number of decimal places shown, especially for things like prices or scientific measurements.

The syntax for this is :.{precision}f, where precision is the number of decimal places you want.

price = 59.95
tax = price * 0.0725

print(f"Raw tax value: {tax}")
print(f"Formatted for currency: ${tax:.2f}")

The output shows how the format specifier rounds the number appropriately:

Raw tax value: 4.346375
Formatted for currency: $4.35

Padding and Zero-Padding

Sometimes you want a number to take up a certain number of spaces, which is useful for aligning text in a report. You can also pad with leading zeros, which is common for file names.

The syntax for zero-padding is :0{width}d.

print("Generating filenames:")
for i in range(1, 4):
    # This formats the number 'i' to have a width of 3, padded with zeros
    print(f"File_{i:03d}.txt")

This produces nicely aligned filenames:

Generating filenames:
File_001.txt
File_002.txt
File_003.txt

Formatting Dates

F-strings are also excellent for formatting date and time objects into human-readable strings. To work with dates, we first need to import Python’s built-in datetime module.

The format specifier for dates uses special codes prefixed with a %, like %Y for the full year and %m for the month number.

import datetime

now = datetime.datetime.now()

print(f"Default representation: {now}")
print(f"USA format (MM/DD/YYYY): {now:%m/%d/%Y}")
print(f"ISO format (YYYY-MM-DD): {now:%Y-%m-%d}")
print(f"With time: {now:%Y-%m-%d %H:%M:%S}")

The output is a clean, formatted date string:

Default representation: 2025-10-04 10:36:45.123456
USA format (MM/DD/YYYY): 10/04/2025
ISO format (YYYY-MM-DD): 2025-10-04
With time: 2025-10-04 10:36:45

Quick Reminder: Expressions Inside f-Strings

Finally, let’s not forget one of the most powerful features we touched on in Post #18: you can put any valid Python expression inside the curly braces. This can be combined with format specifiers.

name = "alice"
scores = [88, 92, 100]

# Call the .title() method on the name variable
print(f"Hello, {name.title()}!")

# Perform a calculation and then format the result
print(f"Your average score is {sum(scores) / len(scores):.2f}.")

The output is clean and calculated on the fly:

Hello, Alice!
Your average score is 93.33.

What’s Next?

You’ve now unlocked the full power of f-strings. By using the format specifier mini-language, you can precisely control the presentation of numbers, dates, and other objects, leading to clean, professional-looking output in your programs.

F-strings are perfect for creating a formatted string from a mix of different variables. But what if your task is simpler? What if you just have a list of strings and you want to join them all together into a single string with a separator? For this, Python has a more specialized and highly efficient method. In Post #116, we will learn the Pythonic way to combine a list of strings using the .join() method.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment