Editor settings

General settings

Save settings

Learn to program with Python

Python f-strings #

In Python, an f-string is a string that allows us to write additional code inside a string. An f-string is denoted by an f or F character at the beginning of a string. We can then use the {} to inject a variable or code into the string.

For example, instead of writing this:

name = "James"
sentence = "My name is " + name
print(sentence) # output: My name is James

We can use f-string to print the sentence, like so:

name = "James"
sentence = f"My name is {name}"
print(sentence) # output: My name is James

We can also use any expression within the {} as well.

sentence = f"The total of 20 + 20 is {20 + 20}"
print(sentence) # output: The total of 20 + 20 is 40

Exercise #

  • sentence should be "Python is an amazing programming language."
  • sentence is assigned with f-string
Output will be displayed here