Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Python

Python f-strings: 8 formatting tricks most developers miss

Learn 8 advanced f-string formatting tricks beyond basic variable interpolation — including number formatting, dates, debugging expressions, and real-world report generation — to write cleaner, faster Python code.

July 2026 6 min read 2 views 0 hearts

Python f-strings: The formatting tricks most developers miss

You probably already use Python f-strings. They're the cleanest way to embed variables in strings since Python 3.6. But if you're only doing f"Hello {name}", you're leaving a lot of power on the table.

Let me show you some advanced tricks that will make your code shorter, cleaner, and sometimes even faster. These are real-world techniques I've used at PythonSkillset while building our internal tools.

The basics you should already know

Before we jump into advanced stuff, here's what f-strings can do out of the box:

name = "PythonSkillset"
version = 3.12
print(f"We run {name} on Python {version}")

Simple. But the real magic happens when you use the colon syntax: {variable:format_specifier}

Formatting numbers like a pro

Thousands separators

When you're printing large numbers, readability matters:

revenue = 1234567890
print(f"Annual revenue: {revenue:,}")
# Annual revenue: 1,234,567,890

That comma makes a huge difference. Without it, your eyes have to count digits.

Percentages without the math

Ever calculated percentages manually? F-strings do it for you:

completion = 0.7523
print(f"Progress: {completion:.1%}")
# Progress: 75.2%

The % multiplies by 100 and adds the percent sign. No more * 100 in your code.

Fixed-width formatting for tables

When building reports, alignment matters:

header = f"{'Name':<20} {'Score':>10}"
row1 = f"{'Alice':<20} {95:>10}"
row2 = f"{'Bob':<20} {87:>10}"

The <20 left-aligns in 20 characters, >10 right-aligns in 10. This creates neat columns without any external libraries.

Dates and times made simple

F-strings work with datetime objects too:

from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}")
# 2024-03-15 14:30:22

You can use any strftime code inside the curly braces. This is much cleaner than calling .strftime() separately.

Debugging with self-documenting expressions

This is my favorite feature from Python 3.8:

user_count = 847
active_users = 623
print(f"{user_count=}, {active_users=}")
# user_count=847, active_users=623

The = sign prints both the variable name and its value. This is perfect for debugging — no more writing print("user_count:", user_count).

You can combine it with formatting:

print(f"{active_users / user_count:.1%}")
# But also:
print(f"{active_users / user_count=:.1%}")
# active_users / user_count=73.6%

Calling functions inside f-strings

Yes, you can put function calls directly inside the braces:

def get_discount(price):
    return price * 0.1

price = 499.99
print(f"Your discount: ${get_discount(price):.2f}")
# Your discount: $49.99

But be careful — don't put complex logic there. It makes code hard to read. Simple calls only.

Escape the curly braces

Need literal curly braces? Double them up:

name = "PythonSkillset"
print(f"{{name}} is {name}")
# {name} is PythonSkillset

This comes in handy when generating JSON or LaTeX code.

Real-world example: Building a report

Here's how I combine these tricks at PythonSkillset to generate automated reports:

def generate_report(users, revenue, conversion):
    report = f"""
    {'Metric':<25} {'Value':>15}
    {'-'*40}
    {'Total Users':<25} {users:>15,}
    {'Revenue':<25} ${revenue:>13,.2f}
    {'Conversion Rate':<25} {conversion:.2%}
    """
    return report

print(generate_report(12738, 93452.67, 0.0834))

The output looks professional with clean alignment, commas, percentages, and currency formatting — all in a single f-string.

Performance tip: Use f-strings over .format()

F-strings are evaluated at runtime, but they're generally faster than .format() because Python compiles them into efficient bytecode. In benchmarks, f-strings are about 2-3x faster for simple cases.

Watch out for security

Never use user input directly inside f-strings. Since f-strings evaluate expressions, malicious input could execute arbitrary code. Always sanitize or use str() on user data before interpolation.

What's next?

Play around with these patterns in your own code. Start with number formatting and the debug = trick — they'll immediately improve your daily workflow. Once you're comfortable, try building a formatted table or a currency report.

The beauty of f-strings is that they're just Python — no new syntax to learn, just smarter use of what's already there.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.