Python String Formatting

🧵 Python String Formatting

String formatting means inserting values into a string in a clean and readable way.

Python supports 4 main formatting methods:

  1. f-strings (Recommended, fastest)

  2. format() method

  3. % formatting (Old style)

  4. Template Strings (less common but safe)


✅ 1. F-Strings (Best Way — Python 3.6+)


 

💡 Supports expressions:

print(f"5 + 5 = {5 + 5}")

💡 With formatting:

price = 49.95789
print(f"Price: {price:.2f}") # 2 decimal places

🧮 Format Numbers

Format Usage Example
{:.2f} 2 decimals 3.14159 → 3.14
{:,.2f} Commas + decimals 10000 → 10,000.00
{:b} Binary 5 → 101
{:x} Hexadecimal 16 → 10

Example:

num = 12345.6789
print(f"Formatted: {num:,.2f}")

🧩 2. .format() Method

text = "Hello, {}!"
print(text.format("Python"))

Positional & Named Formatting

name = "Vipul"
age = 25
print(“My name is {} and I am {} years old.”.format(name, age))

Using indexes:

print("Hello {1}, you are {0} years old.".format(age, name))

Named arguments:

print("My name is {name} and age is {age}.".format(name="Raj", age=22))

🎨 Format Numbers with .format()

print("The price is {:.2f}".format(49.95789))
print("Binary of 5 is {:b}".format(5))

🧓 3. % Formatting (Old Style)

name = "Vipul"
age = 25
print(“My name is %s and I am %d years old.” % (name, age))
Symbol Meaning
%s string
%d integer
%f float

Formatting floats:

print("Price: %.2f" % 49.95789)

🛡 4. Template Strings (From string module)

Useful in financial or user input-sensitive programs.

from string import Template

template = Template(“Hello $name, welcome!”)
print(template.substitute(name=“Vipul”))


📍 Alignment & Formatting

Syntax Meaning
{:>10} Right align
{:<10} Left align
{:^10} Center align

Example:



🔥 Real Example

name = "Vipul"
marks = 88.567
message = f”Student: {name}\nMarks: {marks:.1f}%”
print(message)

📌 Summary Table

Method Use Case Modern Use
F-string Best, fast, clean ⭐⭐ Recommended
.format() Flexible formatting ⭐ Used
% formatting Old Python ⚠ Legacy
Template Strings Secure formatting ⭐ Special use

🧠 Practice Tasks

✔ Format currency with commas
✔ Display a table using alignment
✔ Create a dynamic message using user input
✔ Convert number to binary & hex using formatting

You may also like...