F-Strings Tricks You Didn’t Know

·

·

F-Strings Tricks You Didn’t Know

F-strings are one of Python’s most loved features, but many developers don’t realize how powerful they really are beyond simple string interpolation. Many developers started with the basics — dropping variables into strings with an f prefix. It is Simple, clean, readable.

But as I worked on more projects, I discovered that f-strings could do so much more — from formatting numbers and dates to even calling functions inside the braces. These little tricks saved me from writing messy code and made debugging a lot easier. All codes in this blog were tested and come from my personal python notes.

So if you’re already using f-strings but only for the basics, Here are some hidden gems you might not know about.

Trick 1: Formatting Numbers

This feature is useful when dealing with financial data where Python spat out numbers with too many decimal places:

  • .2f → 2 decimal places
  • .3f → 3 decimal places
  • , → Add commas for readability
price = 1234.56789
print(f"Price: {price:.2f}")
big_number = 1000000
print(f"Total: {big_number:,}")

Output:

Price: 1234.57
Total: 1,000,000

Trick 2: Aligning Text and Numbers

When I was writing scripts that output logs, it would be very readable when things line up nicely. F-strings fix that with alignment:

  • < → Left align
  • > → Right align
  • ^ → Center align
for fruit, qty in [("Apple", 5), ("Banana", 120), ("Cherry", 40)]:
    print(f"{fruit:<10} | {qty:>5}")

Output:

Apple      |     5
Banana     |   120
Cherry     |    40

Trick 3: Debugging Made Easy (= Operator)

One of the best debugging features is the = operator in f-strings.

user = "alice"
score = 95
print(f"{user=}, {score=}")

Output:

user='alice', score=95

This trick has saved me countless hours when printing multiple variables. No more print("user:", user, "score:", score) — just one clean line.

Trick 4: Embedding Expressions

You can run expressions right inside f-strings.

x, y = 5, 10
print(f"The sum of {x} and {y} is {x + y}")

Output:

The sum of 5 and 10 is 15

Trick 5: Working with Dates and Times

Instead of messing with strftime, you could do this:

  • %Y → Year
  • %m → Month
  • %d → Day
  • %H:%M:%S → Hour:Minute:Second
from datetime import datetime
now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")

Output:

Current time: 2025-08-21 11:23:45

This little trick keeps my logs human-friendly.

Trick 6: Dynamic Formatting

F-strings even let you use variables inside formatting specifiers.

width = 10
value = 42
print(f"{value:{width}}")

Output:

width = 10
value = 42
print(f"{value:{width}}")

Trick 7: Calling Functions Directly

you can even call functions inside f-strings

def shout(text):
    return text.upper() + "!"

word = "python"
print(f"{shout(word)} is awesome")

Output:

PYTHON! is awesome