You're asking a great question, as f-strings are very powerful for including variables in your output!
Here's how you use f-strings with variables, based on the example in your current step:
- Start with
forF: Place anf(for "formatted") orFdirectly before the opening quotation mark of your string literal.f"Your text here" - Embed Variables with Curly Braces
{}: Inside the f-string, you can directly embed the names of your variables (or even Python expressions) by placing them within curly braces{}.
Let's look at the example from the step:
books = 5
print(f"I have {books} books.")
- First, we define a variable
booksand set its value to5. - Then, in
print(f"I have {books} books."), we usef"to start the f-string. - Inside the string,
{books}tells Python to look up the value of thebooksvariable (which is5) and insert it directly into that spot in the string.
The output will be: I have 5 books.
You can also use multiple variables in one f-string:
name = "Labby"
age = 2
print(f"Hello, my name is {name} and I am {age} years old.")
Output:
Hello, my name is Labby and I am 2 years old.
F-strings are very convenient because you don't need to concatenate strings with + or use .format() methods, making your code cleaner and easier to read.
Did that explanation help clarify how to use f-strings with variables? Feel free to try another example!