Python provides several powerful ways to insert variables and expressions into strings dynamically.
The most popular and modern approaches are using f-strings (since Python 3.6) and the str.format() method (available since Python 2.6).
Both are used for string formatting β i.e., embedding values into strings cleanly and efficiently.
πΉ 1. Using f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings allow you to embed variables, expressions, and even function calls inside strings using {} braces.
Syntax:
f"string {variable}"π§© Example 1: Basic f-string
name = "Dheeraj"
age = 24
print(f"My name is {name} and I am {age} years old.")Output:
My name is Dheeraj and I am 24 years old.π§© Example 2: Using Expressions Inside f-Strings
a = 10
b = 5
print(f"The sum of {a} and {b} is {a + b}.")Output:
The sum of 10 and 5 is 15.π§© Example 3: Calling Functions Inside f-Strings
def greet(name):
return f"Hello, {name}!"
print(f"{greet('Dheeraj')} Welcome to Python!")Output:
Hello, Dheeraj! Welcome to Python!π§© Example 4: Formatting Numbers
price = 49.9589
print(f"Price: {price:.2f}") # 2 decimal placesOutput:
Price: 49.96π§© Example 5: Date Formatting with f-Strings
import datetime
today = datetime.date.today()
print(f"Today's date is {today:%d-%m-%Y}")Output:
Today's date is 09-11-2025β Advantages of f-Strings:
- Fastest string formatting method in Python.
- More readable and concise.
- Supports inline expressions and function calls.
- Preferred in Python 3.6+.
πΉ 2. Using str.format() Method
The format() method provides another way to substitute variables and expressions into strings using {} placeholders.
Syntax:
"string {}".format(value)π§© Example 1: Basic Usage
name = "Dheeraj"
age = 24
print("My name is {} and I am {} years old.".format(name, age))Output:
My name is Dheeraj and I am 24 years old.π§© Example 2: Positional Indexing
print("I love {0} and {1}.".format("Python", "Cybersecurity"))
print("{1} is better than {0}.".format("Java", "Python"))Output:
I love Python and Cybersecurity.
Python is better than Java.π§© Example 3: Keyword Arguments
print("My name is {name} and I am from {city}.".format(name="Dheeraj", city="Delhi"))Output:
My name is Dheeraj and I am from Delhi.π§© Example 4: Formatting Numbers
pi = 3.1415926
print("Pi value: {:.2f}".format(pi)) # 2 decimal placesOutput:
Pi value: 3.14π§© Example 5: Alignment and Padding
print("{:<10}".format("left")) # Left aligned
print("{:^10}".format("center")) # Center aligned
print("{:>10}".format("right")) # Right alignedOutput:
left
center
rightπ§© Example 6: Using Dictionary with Format
info = {"name": "Dheeraj", "age": 24}
print("Name: {name}, Age: {age}".format(**info))Output:
Name: Dheeraj, Age: 24β
Advantages of format()
- Works in both Python 2 and 3.
- Supports positional and keyword arguments.
- More flexible than old
%formatting. - Supports advanced formatting features like padding and alignment.
πΉ 3. Using % Formatting (Old Method)
Before format() and f-strings, Python used C-style formatting with the % operator.
π§© Example:
name = "Dheeraj"
age = 24
print("My name is %s and I am %d years old." % (name, age))Output:
My name is Dheeraj and I am 24 years old.β
Still works but is not recommended β less readable and limited compared to format() or f-strings.
πΉ Comparison Table
| Feature | % Formatting | str.format() | f-Strings |
|---|---|---|---|
| Introduced In | Python 1 | Python 2.6 | Python 3.6 |
| Syntax Simplicity | Moderate | Verbose | Very simple |
| Performance | Slower | Moderate | Fastest |
| Supports Expressions | No | Limited | Yes |
| Supports Type Hints | Limited | Yes | Yes |
| Recommended? | β Deprecated | β Good | β β Best (modern way) |
β In Summary
| Method | Example | Best Used When |
|---|---|---|
| f-String | f"Name: {name}, Age: {age}" | Python β₯ 3.6; modern, fast, readable |
format() | "Name: {}, Age: {}".format(name, age) | Python 2.x / 3.x compatibility |
% Operator | "Name: %s, Age: %d" % (name, age) | Legacy code (avoid for new code) |
β In short:
Use f-strings for modern Python β theyβre fast, clean, and powerful.
Useformat()for compatibility with older versions.
Avoid%formatting in new projects.
