The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
Python string formatting allows you to insert variables or expressions into strings dynamically — instead of concatenating manually.
There are four main ways to format strings in Python, each evolving with the language.
1. Old Style Formatting (% Operator)
This is similar to C’s printf formatting.
name = "Anna"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Anna and I am 25 years old.
Common format specifiers:
Specifier
Meaning
Example Output
%s
String
'Anna'
%d
Integer
25
%f
Floating-point
25.000000
%.2f
2 decimal places
25.00
2. str.format() Method (Introduced in Python 2.6+)
This method uses {} placeholders inside strings.
name = "Anna"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Anna and I am 25 years old.
You can also use indexes or named arguments:
print("My name is {0} and I am {1} years old. {0} loves Python.".format(name, age))
print("My name is {name} and I am {age} years old.".format(name="Anna", age=25))
Formatting numbers:
pi = 3.1415926
print("Pi rounded to 2 decimals: {:.2f}".format(pi))
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
There are four main ways to format strings in Python, each evolving with the language.
1. Old Style Formatting (
%Operator)This is similar to C’s
printfformatting.Output:
Common format specifiers:
%s'Anna'%d25%f25.000000%.2f25.002.
str.format()Method (Introduced in Python 2.6+)This method uses
{}placeholders inside strings.Output:
You can also use indexes or named arguments:
Formatting numbers:
Output:
3. Formatted String Literals (f-Strings) — Python 3.6+
This is the modern and most readable way.
You prefix the string with
forF, and expressions inside{}are evaluated directly.Output:
You can also use expressions inside
{}:Number formatting:
Output:
Alignment and width:
Output:
4. Template Strings (from
stringmodule)Useful when you want safe substitutions (e.g., user input).
Output:
If you use
.safe_substitute()instead, it won’t raise an error if a placeholder is missing.Comparison Summary
%"Hello %s" % name.format()"Hello {}".format(name)f""f"Hello {name}"TemplateTemplate("Hello $name")Example Summary