There are three primary ways to handle string formatting, with f-strings being the modern, industry-standard approach.
An f-string (short for formatted string literal) is a string prefixed with the letter
forF.It allows you to embed Python expressions directly inside curly braces
{}.
Method | Syntax Example | Notes |
|---|---|---|
|
| Oldest method (C-style); hard to read with multiple variables. |
|
| Introduced in Python 2.6; better, but can become verbose. |
|
| Modern Standard (Python 3.6+); cleanest, fastest and most powerful. |
# Ex1:
name, score = "Ritesh", 0.9234
print(f"{name}: {score:.2%}") # Ritesh: 92.34%
# Ex2:
name = "Alice"
age = 30
# Elegant, clean inline variables
message = f"My name is {name} and I am {age} years old."
print(message) #My name is Alice and I am 30 years old.
print(f"Next year I will be {age + 1}.") # Output: Next year I will be 23.
print(f"Shouting my name: {name.upper()}") # Output: Shouting my name: RITESH