f-Strings
In the last challenge, you output a message by passing necessary variables as string parts. Concatenation is a good approach, but wouldn't it be easier to pass variables within a string pattern, as if you’re completing a puzzle?
Python provides us with such functionality. The approach is called f-strings. To use a variable value inside the string, place the f
letter to the left of the opening quotes and pass the variable's name within curly brackets {}
inside the string. For example, let's output the message 'Player Alex has level 16', where Alex and 16 are stored in variables.
12345# Initial variables name = "Alex" level = 16 # Output message using f-string print(f"Player {name} has level {level}.")
As you can see, you shouldn't worry about using strings and numerical values simultaneously with this approach.
Using the same variables as in the previous chapter-challenge (name
and age
), output the same message as before ("name is age y.o.").
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Stel mij vragen over dit onderwerp
Vat dit hoofdstuk samen
Toon voorbeelden uit de praktijk
Awesome!
Completion rate improved to 4
f-Strings
Veeg om het menu te tonen
In the last challenge, you output a message by passing necessary variables as string parts. Concatenation is a good approach, but wouldn't it be easier to pass variables within a string pattern, as if you’re completing a puzzle?
Python provides us with such functionality. The approach is called f-strings. To use a variable value inside the string, place the f
letter to the left of the opening quotes and pass the variable's name within curly brackets {}
inside the string. For example, let's output the message 'Player Alex has level 16', where Alex and 16 are stored in variables.
12345# Initial variables name = "Alex" level = 16 # Output message using f-string print(f"Player {name} has level {level}.")
As you can see, you shouldn't worry about using strings and numerical values simultaneously with this approach.
Using the same variables as in the previous chapter-challenge (name
and age
), output the same message as before ("name is age y.o.").
Bedankt voor je feedback!