In Python (programming language), string formatting is used to insert variables or values into a string in a clean and readable way.

It is commonly used when printing messages, displaying results, or building dynamic text.

Example:

name = "Rahul"
age = 20

print("My name is", name, "and I am", age, "years old.")

Output

My name is Rahul and I am 20 years old.

Python provides several methods for formatting strings.


1️⃣ Using Commas in print()

This is the simplest method.

name = "Rahul"
age = 20

print("My name is", name, "and I am", age, "years old.")

Output

My name is Rahul and I am 20 years old.

2️⃣ Using format() Method

The format() method inserts values into placeholders {}.

name = "Rahul"
age = 20

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

Output

My name is Rahul and I am 20 years old

Using Index Numbers

name = "Rahul"
age = 20
text = "My name is {0} and I am {1} years old".format(name, age)

print(text)

3️⃣ Using f-Strings (Recommended)

f-strings are the modern and easiest way to format strings.

name = "Rahul"
age = 20

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

Output

My name is Rahul and I am 20 years old

4️⃣ Formatting Numbers

You can format numbers using f-strings.

Example: Decimal Formatting

price = 49.56789

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

Output

Price: 49.57

.2f means 2 decimal places.


5️⃣ Padding Numbers

num = 7

print(f"{num:03}")

Output

007

6️⃣ Aligning Text

text = "Python"

print(f"{text:<10}")
print(f"{text:>10}")
print(f"{text:^10}")

Output

Python    
Python
Python

Explanation:

SymbolMeaning
<Left align
>Right align
^Center align

⭐ Example Program

name = "Rahul"
score = 95.456

print(f"Student: {name}")
print(f"Score: {score:.2f}")

Output

Student: Rahul
Score: 95.46

βœ… Summary

MethodExample
Commaprint("Hi", name)
format()"Hi {}".format(name)
f-Stringf"Hi {name}"

⭐ Best Practice: Use f-strings because they are faster and easier to read.