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 places

Output:

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 places

Output:

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 aligned

Output:

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% Formattingstr.format()f-Strings
Introduced InPython 1Python 2.6Python 3.6
Syntax SimplicityModerateVerboseVery simple
PerformanceSlowerModerateFastest
Supports ExpressionsNoLimitedYes
Supports Type HintsLimitedYesYes
Recommended?❌ Deprecatedβœ… Goodβœ…βœ… Best (modern way)

βœ… In Summary

MethodExampleBest Used When
f-Stringf"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.
Use format() for compatibility with older versions.
Avoid % formatting in new projects.

Scroll to Top