🐍1.2 String Formatting in Python
Mastering String Formatting in Python
String formatting is an essential feature in Python that helps in constructing dynamic strings efficiently. Python provides multiple ways to format strings, each with its own advantages. In this blog, we'll explore all possible ways of string formatting with examples.
1️⃣ Using % Operator (Old Style Formatting)
The %
operator is the oldest way of formatting strings in Python. It works similarly to C's printf-style formatting.
Syntax:
"format_string" % values
Example:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Alice and I am 25 years old.
2️⃣ Using .format()
Method
Python introduced the .format()
method to replace %
formatting. It provides more flexibility and readability.
Syntax:
"{} {}".format(value1, value2)
Example:
name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Bob and I am 30 years old.
Using Positional and Keyword Arguments:
print("{1} is {0} years old.".format(40, "Charlie"))
print("{name} is {age} years old.".format(name="David", age=35))
Output:
Charlie is 40 years old.
David is 35 years old.
3️⃣ Using f-strings (Formatted String Literals) - Best Practice
f-strings were introduced in Python 3.6 and provide a concise and readable way to format strings.
Syntax:
f"string {variable}"
Example:
name = "Eve"
age = 28
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Eve and I am 28 years old.
Using Expressions Inside f-strings:
x, y = 5, 10
print(f"The sum of {x} and {y} is {x + y}.")
Output:
The sum of 5 and 10 is 15.
Formatting Numbers with f-strings:
number = 1234.56789
print(f"Rounded: {number:.2f}") # 2 decimal places
print(f"Currency: ${number:,.2f}") # Thousand separator
Output:
Rounded: 1234.57
Currency: $1,234.57
4️⃣ Using String Padding and Alignment
String formatting allows padding with spaces or characters for proper alignment.
Left, Right, and Center Alignment with f-strings:
text = "Hello"
print(f"{text:<10}") # Left aligned
print(f"{text:>10}") # Right aligned
print(f"{text:^10}") # Center aligned
Output:
Hello
Hello
Hello
5️⃣ Using .format()
for Number Formatting
num = 42
print("Binary: {:b}, Octal: {:o}, Hex: {:x}".format(num, num, num))
Output:
Binary: 101010, Octal: 52, Hex: 2a
6️⃣ Using str.zfill()
for Zero Padding
num = 5
print(str(num).zfill(4)) # Pads with leading zeros
Output:
0005
1. Escaping Quotes in Strings
Sometimes, we need to include quotes inside a string. This can be done using escape characters (\
):
print("He said, \"What's this?\"")
print('He said, "what\'s this?"')
print("He said, \"What's there?\"")
Output:
He said, "What's this?"
He said, "what's this?"
He said, "What's there?"
2. Basic String Formatting
String formatting allows us to insert variables into a string efficiently:
a = 10
b = 15
print(a, "is smaller than", b)
print(str(a) + " is smaller than " + str(b))
print("{} is smaller than {}".format(a, b))
Output:
10 is smaller than 15
10 is smaller than 15
10 is smaller than 15
3. Using format()
with SQL Query
query = "INSERT INTO abc() VALUES('{}',{}, {})".format(a, b, 10.34)
print(query)
Output:
INSERT INTO abc() VALUES('10',15,10.34)
4. Positional and Keyword Formatting
Using positional and keyword arguments in format()
:
print("{2}, {0} and {1}".format('John', 'Bill', 'Rooma'))
print("{s1}, {b1} and {j1}".format(j1='John', b1='Bill', s1='Sean'))
Output:
Rooma, John and Bill
Sean, Bill and John
5. Float Formatting
Format floating-point numbers to specific decimal places:
a = 10.76
b = 220.5666666
print("Two float numbers: {:.2f} & {:.3f}".format(a, b))
Output:
Two float numbers: 10.76 & 220.567
6. Formatting Numbers with Padding
amount = 10235
interest_rate = 7.25
total_amount = (amount * interest_rate) / 100
print("{:.2f}".format(total_amount))
Output:
742.54
7. Old-Style String Formatting (%
Operator)
This method is inspired by C's printf-style formatting:
name = "John"
print("Hello, %s" % name)
Output:
Hello, John
8. Binary, Octal, and Hexadecimal Formatting
Format numbers into different bases:
print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))
Output:
bin: 1100, oct: 14, hex: c
Explanation:
{:b}
→ Converts num
to binary (base 2).
42
in binary → 101010
{:o}
→ Converts num
to octal (base 8).
42
in octal → 52
{:x}
→ Converts num
to hexadecimal (base 16).
42
in hex → 2a
(lowercase)
{}
placeholders are replaced by the num
value.
9. Number Formatting with Padding
print("{:+10.2f}".format(-12.2346))
print("{:06d}".format(12))
Output:
-12.23
000012
10. String Padding and Alignment
Align text with spaces or custom characters:
print("{:^10}".format("cat"))
print("{:-^30}".format("cat"))
Output:
cat
-----------cat------------
11. F-Strings (Python 3.6+)
F-strings provide a concise and readable way to format strings:
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.
12. Formatting Dates and Times
from datetime import datetime
date = datetime(2025, 3, 8, 14, 30)
print(f"Today is {date:%A, %B %d, %Y} at {date:%I:%M %p}")
Output:
Today is Saturday, March 08, 2025 at 02:30 PM
Explanation:
%A
→ Full weekday name (e.g., "Saturday").
%B
→ Full month name (e.g., "March").
%d
→ Day of the month with leading zeros (e.g., "08").
%Y
→ Four-digit year (e.g., "2025").
%I
→ Hour (12-hour format, with leading zero if needed).
%M
→ Minutes (with leading zero).
%p
→ AM/PM indicator.
13. Using format_map()
with Dictionaries
data = {"name": "Bob", "age": 30}
print("My name is {name} and I am {age} years old.".format_map(data))
Output:
My name is Bob and I am 30 years old.
14. Formatting Large Numbers with Comma
num = 1000000
print("{:,}".format(num))
Output:
1,000,000
Conclusion
Python provides multiple ways to format strings, each suited to different use cases:
%
Formatting (Old but still useful).format()
Method (More flexible and readable)- f-strings (Recommended for Python 3.6+)
- Padding and Alignment for better string formatting
- Numeric Formatting for different bases
Mastering these techniques will enhance your Python skills and improve code readability. 🚀
Comments
Post a Comment