Formatting Strings with F-Strings
In this lesson, you will learn how to embed variables directly into strings to create dynamic messages effortlessly.
Previously, you learned that you can combine strings using concatenation (+), but this can become messy and difficult to read when you need to mix text with numbers or variables. Python provides a much cleaner solution called f-strings (formatted string literals).
How to Use F-Strings
To create an f-string, you 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 inside curly braces {}. Python will look at the variable, grab its current value, and place it directly into the string for you.
Here is an example:
name = "Alex"
score = 95
# Using an f-string to combine text and variables
message = f"Hello {name}, your score is {score}."
print(message)
In this code, Python replaces {name} with "Alex" and {score} with 95. The result is the string "Hello Alex, your score is 95.".
Why Use F-Strings?
F-strings are much more readable than using + or conversion functions like str(). Because f-strings treat the contents of the curly braces as Python expressions, they automatically handle the conversion for you, even if you are embedding numbers or other data types. It makes your code look exactly like the final output you want to see, which helps avoid typos and keeps your logic clean.
You can even perform simple operations inside the braces if needed, such as f"Next year, you will be {age + 1} years old.". This makes f-strings a powerful tool for building messages dynamically as your program runs.
Key Takeaway: Use the f prefix before your string and wrap variables in curly braces {} to insert their values directly into your text with ease.