TalentJR

Lesson 9

Advanced String Formatting

f-strings and formatting numbers

1What Is String Formatting?✨

String formatting allows you to create dynamic strings by embedding variables directly into text. This makes your programs more flexible and interactive!

2Using f-Strings🎯

One of the easiest ways to format strings in Python is with f-strings, or formatted string literals. You create an f-string by placing an 'f' before the opening quote. Here’s how it works:

💻 code
name = "Alice"
age = 12
print(f"{name} is {age} years old.")

This will output: Alice is 12 years old.

3Embedding Expressions💡

You can also include expressions directly inside f-strings. This allows you to perform calculations on the fly:

💻 code
x = 5
y = 10
print(f"The sum of {x} and {y} is {x + y}.")

This will output: The sum of 5 and 10 is 15.

4Formatting Numbers🚀

f-strings can format numbers in different ways, like setting decimal places. Here’s an example of formatting a float to two decimal places:

💻 code
price = 19.99
print(f"The price is ${price:.2f}.")

This will output: The price is $19.99.

5Using Dictionaries with f-Strings🔍

You can also format strings using values from dictionaries. This makes it easy to create messages based on user data:

💻 code
user = {"name": "Bob", "age": 14}
print(f"{user['name']} is {user['age']} years old.")

This will output: Bob is 14 years old.

6What You'll Learn Next⭐

  • ✓ More advanced data handling techniques
  • ✓ Working with files and exceptions
  • ✓ Creating your own modules
  • ✓ Object-oriented programming basics

🎯 Practice Challenges

Master Advanced String Formatting by completing all 3 difficulty levels

🟢 EASY

Advanced String Formatting - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

Advanced String Formatting - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

Advanced String Formatting - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master Advanced String Formatting? 🚀

Complete the challenges, take the quiz and keep your learning streak going!