Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
String Basics & CreationString Indexing & SlicingCommon String MethodsString Formatting EssentialsFinding & Replacing TextString Testing & ValidationRegular Expression BasicsText Splitting & JoiningPractical String Projects
Python/String Manipulation/String Formatting Essentials

🎨 String Formatting Essentials — Create Dynamic Text

String formatting lets you embed variables and values into strings. Python offers three main approaches.


🎯 F-Strings (Recommended)

F-strings (formatted string literals) are the modern, readable way. Add `f` before the quote and wrap variables in `{}`:

name = "Alice"
age = 30

# Simple f-string
message = f"My name is {name} and I'm {age} years old."
print(message)  # My name is Alice and I'm 30 years old.

# Expressions inside braces
print(f"Next year I'll be {age + 1}")  # Next year I'll be 31
print(f"My name in caps: {name.upper()}")  # My name in caps: ALICE

💡 .format() Method

The `.format()` method works on any string:

name = "Bob"
score = 95

# Positional arguments
message = "Hello {}, your score is {}".format(name, score)
print(message)  # Hello Bob, your score is 95

# Named arguments
message = "Hello {n}, your score is {s}".format(n=name, s=score)
print(message)  # Hello Bob, your score is 95

# Reusing arguments
print("{0} likes {1}. {1} is fun!".format("Python", "coding"))
# Python likes coding. Coding is fun!

🎨 % Formatting (Legacy)

The oldest method using `%` operators. Still seen in older code:

name = "Charlie"
age = 25

message = "Hello %s, you are %d years old" % (name, age)
print(message)  # Hello Charlie, you are 25 years old

# Format specifiers: %s (string), %d (integer), %f (float)
price = 19.99
print("Price: $%.2f" % price)  # Price: $19.99

🔑 Formatting Numbers

Control decimal places, padding, and alignment:

# Decimal places
value = 3.14159
print(f"{value:.2f}")    # 3.14
print(f"{value:.4f}")    # 3.1416

# Zero-padding
number = 42
print(f"{number:05d}")   # 00042

# Alignment
text = "Python"
print(f"{text:>10}")     # "    Python" (right-aligned)
print(f"{text:<10}")     # "Python    " (left-aligned)
print(f"{text:^10}")     # "  Python  " (centered)

📊 Formatting Comparison

MethodProsConsExample
F-stringsReadable, fast, modernPython 3.6+ only`f"{name} is {age}"`
.format()Works in older PythonMore verbose`"{} is {}".format(name, age)`
% formattingLegacy compatibleHard to read`"%s is %d" % (name, age)`

💡 Real-World Examples

# Display financial data
amount = 1234.5678
currency = "USD"
print(f"Total: {amount:,.2f} {currency}")  # Total: 1,234.57 USD

# Format table-like data
items = [("Apple", 2.99), ("Banana", 0.50), ("Orange", 1.25)]
for item, price in items:
    print(f"{item:<10} ${price:>6.2f}")
# Apple          $  2.99
# Banana         $  0.50
# Orange         $  1.25

# Build a URL dynamically
user_id = 123
print(f"https://api.example.com/users/{user_id}")
# https://api.example.com/users/123

🔑 Key Takeaways

ConceptRemember
F-strings are bestUse `f""` for new code; it's readable and fast
Use .format()When you need Python 3.5 compatibility
% formattingRecognize it in legacy code; avoid for new projects
Decimal precisionUse `:.2f` for 2 decimal places
Alignment mattersUse `<`, `>`, `^` for left, right, center alignment

🔗 What's Next?

Now learn how to find and replace text efficiently.


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn