How to use f-strings with variables?

QuestionsQuestions8 SkillsProDec, 10 2025
0112

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:

  1. Start with f or F: Place an f (for "formatted") or F directly before the opening quotation mark of your string literal.
    f"Your text here"
  2. 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 books and set its value to 5.
  • Then, in print(f"I have {books} books."), we use f" to start the f-string.
  • Inside the string, {books} tells Python to look up the value of the books variable (which is 5) 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!

0 Comments

no data
Be the first to share your comment!