Many times we will dynamically generate some text using variables. We have done this in previous lessons using string concatenation. Let's see one more example:
name = "Andy"
pet = "dog"
breed = "poodle"
message = "Hey, " + name + "! Nice " + pet + "! Is it a " + breed + "?"
print(message) # Output: Hey, Andy! Nice dog! Is it a poodle?
While this approach perfectly works, it's not ideal. You can see that as our text gets more complicated, it's harder for the reader to visualize all the concatenations in their head.
This can be achieved much easier with string interpolation.
String Interpolation:
String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like:
Hello {name}, nice to meet you!
you would like to replace the placeholder for name of person with an actual name. This process is called string interpolation.
f-strings:
Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f. This new way of formatting strings is powerful and easy to use.
To use this method, prefix your strings with an f and then use curly braces {} to dynamically insert values into your strings:
name = "Mike"
message = f"Hello {name}, nice to meet you!"
print(message) # Output: Hello Mike, nice to meet you!
With these curly braces, we're defining place holders or holes in our string, and when we run our program these holes will be filled with the value of our variables.
So here we have one place holder or one hole in our string and it is for the value of the name variable.
We can have as many place holders as needed:
name = "Mike"
pet = "cat"
breed = "ragdoll"
message = f"Hey, {name}! Nice {pet}! Is it a {breed}?"
print(message) # Output: Hey, Mike! Nice cat! Is it a ragdoll?
Assignment
Follow the Coding Tutorial and let's practice with string interpolation!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
