Constructing Dynamic Strings with F-strings
In this lesson, you will learn how to build readable, dynamic strings by embedding variables and expressions directly into your text using F-strings.
Previously, you learned how to combine strings using concatenation (the + operator) or by converting numbers into strings. While those methods work, they can become messy and difficult to read as your strings get longer. F-strings (short for "formatted strings") offer a modern, cleaner solution.
To create an F-string, simply place the letter f (or F) immediately before the opening quotation mark of your string. Inside the string, you can place any variable name or Python expression inside a pair of curly braces {}. Python will automatically "evaluate" what is inside those braces, turn it into a string, and insert it into your text at that exact location.
Practical Example
Imagine you have a variable for a user's name and another for their current score:
name = "Alex"
score = 95
# Using an F-string to combine them
message = f"Hello {name}, your current score is {score}!"
print(message)
Output: Hello Alex, your current score is 95!
You aren’t limited to simple variables; you can even perform math or call functions inside the curly braces. For example, if you wanted to show the score for a "bonus level," you could do this:
# Doing math directly inside the string
print(f"If you finish the next level, your score will be {score + 10}.")
Output: If you finish the next level, your score will be 105.
By using F-strings, you avoid the need to manually cast numbers to strings or manage complex concatenation. You simply type the sentence exactly how you want it to look, and let Python fill in the gaps for you.
Key Takeaway: Prepending an f to your string literal allows you to use {} curly braces to inject variables or calculations directly into your text for cleaner, more readable code.