String Formatting Methods in Python
String formatting in Python means inserting variables, numbers, or expressions inside a string in a clean and organized way. It is useful when we want to display dynamic data, such as user names, marks, prices, etc., inside sentences.
1. % Operator Formatting
This is the oldest method of formatting. We use special symbols like %s,
%d, %f etc., where:
%s→ String%d→ Integer%f→ Float
Syntax:
"text %s here" % (value)
Example:
name = "Devanshi"
platform = "ShikshaSanchar"
print("Welcome %s to %s!" % (name, platform))
Output:
Welcome Devanshi to ShikshaSanchar!
Explanation:
%splaceholders are replaced by values from the tuple(name, platform).- Both variables are inserted in the string in the correct order.
2. format() Method
This method inserts values into curly brackets {}. It's more readable and flexible than
% operator.
Syntax:
"{}".format(value)
Example:
name = "Simran"
role = "Educator"
print("Hello {}, you are a {} at ShikshaSanchar.".format(name, role))
Output:
Hello Simran, you are a Educator at ShikshaSanchar.
Explanation:
{}are placeholders for variables.format()method fills the values in the order.
3. f-Strings (Formatted String Literals)
f-Strings are the most modern and clean way to format strings (available from Python 3.6+). We just
write f before the string and insert variables inside {}.
Syntax:
f"text {variable}"
Example:
subject = "Python"
chapter = 6
print(f"Chapter {chapter} of {subject} is live on ShikshaSanchar!")
Output:
Chapter 6 of Python is live on ShikshaSanchar!
Explanation:
- We use
fbefore the string. - Variables can be directly written inside
{}. - Clean, short, and readable format.
Expression Inside f-strings:
You can also write expressions or calculations directly inside {} in
f-strings. This makes it very powerful and reduces extra code.
Example:
a = 10
b = 5
print(f"The sum of {a} and {b} is {a + b}.")
Output:
The sum of 10 and 5 is 15.
Explanation:
{a + b}performs the addition directly inside the string.- You can also use other expressions like
{a * b},{len(name)}, etc. - This saves lines and makes the code clean and readable.
Using format() and f-string()
1. Positional and Keyword Formatting with format()
The format() method in Python allows us to insert values into a string using:
-
Positional Formatting:
A type of string formatting where placeholders like
{0}, {1}, {2}are used inside the string. The values are inserted based on their position in theformat()method.
Example: -
Keyword Formatting (Named Indexing):
A type of formatting where placeholders like
{name},{course}are used and values are passed using keyword arguments. It improves clarity and is useful when the string has many values.
Example:
Example using Positional Formatting:
msg = "Welcome {0} to {1}! You have enrolled in {2} course."
print(msg.format("Angel", "ShikshaSanchar", "Python"))
Welcome Angel to ShikshaSanchar! You have enrolled in Python course.
Explanation:
{0}is replaced by"Angel"{1}is replaced by"ShikshaSanchar"{2}is replaced by"Python"- Values are filled in the order they appear in
format()
Example using Keyword Formatting:
msg = "{user}, you have successfully enrolled in the {course} course on {platform}."
print(msg.format(user="Mukesh", course="Web Development", platform="ShikshaSanchar"))
Mukesh, you have successfully enrolled in the Web Development course on ShikshaSanchar.
Explanation:
{user},{course}, and{platform}are named placeholders.- Values are passed using keyword arguments inside
format(). - This method improves readability, especially when there are many variables.
2. Formatting Numbers with format() or f-strings
Sometimes we want to show numbers in a clean and specific way — like rounding to 2 decimal
places.
Python allows this using format() or f-strings.
For example, on ShikshaSanchar, if a course costs 199.995, we want to show it as
200.00.
Using format() method:
price = 199.995
print("Price: {:.2f}".format(price))
Output:
Price: 200.00
Using f-string:
print(f"Price: {price:.2f}")
Output:
Price: 200.00
Explanation:
:.2fmeans: round the number to 2 digits after decimal.format()andf-stringsboth support this style.- It is useful when displaying prices, percentages, or float values.
Summary: String Formatting Methods
- % Operator: Oldest method. Uses
%s,%d,%fto insert string, integer, float. format()method: Uses curly brackets{}. Supports both:- Positional formatting: Uses
{0},{1}and fills values based on order. - Keyword formatting / Named indexing: Uses
{name},{course}and assigns values using keywords.
- Positional formatting: Uses
- f-Strings: Most modern and clean method. Uses
f"Text {variable}"format. - Expression inside f-strings: You can do calculations directly inside
{}, like{a + b},{price * 0.9}, etc. - Formatting numbers: Works in both
format()andf-stringsusing::.2f→ Round float to 2 decimal places:05d→ Pad integer with zeros (e.g., 00042):.1%→ Show value as percentage