Python Tip: f-strings

Cleaner, faster, and more readable string formatting

Learn how to use f-strings for cleaner, faster, and more readable string formatting with precision control.
Author

Shep Bryan IV

Python Tip: f-strings

Tired of complex string formatting? Use f-strings for cleaner, faster, and more readable code.


Basic f-strings

F-strings (formatted string literals) allow you to quickly insert variables into strings. Just put an f before the string and use curly braces to insert variables.

name = "Bob"
age = 30

# Don't do this
mystring = "Hello, " + name + "! You are " + str(age) + " years old."
print(mystring)

# Do this instead
mystring = f"Hello, {name}! You are {age} years old."
print(mystring)
Hello, Bob! You are 30 years old.
Hello, Bob! You are 30 years old.

Formatting with Precision

You can format numbers with precision using f-strings. Simply add a colon, a number, and a letter to the variable.

# Format float to n decimal places
pi = 3.141592653589793
print(f"π ≈ {pi:.2f}")  # 2 decimal places
print(f"π ≈ {pi:.4f}")  # 4 decimal places
π ≈ 3.14
π ≈ 3.1416
# Format with significant figures
mass_electron = 9.10938356e-31
print(f"m ≈ {mass_electron:.2g}")  # 2 significant figures
print(f"m ≈ {mass_electron:.4g}")  # 4 significant figures
m ≈ 9.1e-31
m ≈ 9.109e-31
# Format integer with padding
print(f"Answer = {42:02d}")  # Pad to 2 digits
print(f"Answer = {42:04d}")  # Pad to 4 digits
Answer = 42
Answer = 0042
# Format dates
from datetime import datetime
print(f"Today: {datetime.now():%Y-%m-%d}")
Today: 2026-04-30

Wrap-Up

Now you can use f-strings to format strings with ease, precision, and readability.

Follow me for more tips.
Shep Bryan IV