Python String Formatting – Insert Values into Strings Easily

String formatting lets you insert variables into strings in a clean, readable way — instead of messy concatenation.



3 Main Ways to Format Strings in Python :

1. f-string

(Fastest & Most Recommended – Python 3.6+)

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

#Output - 
My name is Alice and I am 25 years old.

Supports expressions too :

print(f"In 5 years, I will be {age + 5} years old.")


2. format( )

Method (Compatible with older versions)

name = "Vikas"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

You can also use positional or named arguments :

print("My name is {1} and I am {0} years old.".format(age, name))  # Positional
print("My name is {n} and I am {a} years old.".format(n=name, a=age))  # Named

3. % Operator

(Old Style – Not Recommended Today)

name = "Shivansh"
age = 25
print("My name is %s and I am %d years old." % (name, age))


Code Meaning
%s String
%d Integer
%f Float (decimal)


Formatting Numbers

With f-string :

price = 49.9999
print(f"Price: ₹{price:.2f}")  # ₹49.99


With format( ) :

print("Price: ₹{:.2f}".format(price))


Summary Table



Method Syntax Example Notes
f-string f"Hello {name}" Modern, clean, efficient
format() "Hello {}".format(name) Flexible, older syntax
% formatting "Hello %s" % name Outdated, not recommended


Practice Python Code Here: