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:
| Symbol | Meaning |
|---|---|
< | 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
| Method | Example |
|---|---|
| Comma | print("Hi", name) |
format() | "Hi {}".format(name) |
| f-String | f"Hi {name}" |
β Best Practice: Use f-strings because they are faster and easier to read.