A Brief How-To

Whether Python is your first programming language or you’ve already got a few languages under your belt, string interpolation is a fun and necessary tool to learn.

For those unsure, string interpolation gives you the ability to inject variables directly into a string. This means, for example, that you can dynamically print strings rather than hard coding them. The below function, for example, lets you print out names dynamically.

def print_name(name):
print(f"Hi, {name}! How are you?")

The Modulo

There are a few different ways to interpolate in Python. The first we’ll go over involves the modulo % .

print("I can inject %s here." %'anything')
#I can inject anything here

%s acts like a placeholder for a Python object, which can be a variable, number, string etc. At the end of your string after the modulo, you can place any Python object, and it will be injected into your string. %s converts Python objects to strings. You can read more about that here.

The .format() method

.format() is a more dynamic way to achieve the same effect.

print("I can inject {} here. It's pretty {}.".format('anything', 'lit')
#I can inject anything here. It's pretty lit.

Simply place .format() at the end of your string, and add {} curly braces anywhere you want to inject an object. By default, the objects will be injected in the order which they are listed in .format() . However, you can also specify where to to inject them using their index position.

print("I can inject {1} here. It's pretty {0}.".format('lit', 'anything')
#I can inject anything here. It's pretty lit.

You can also assign them keywords.

print("I can inject {var1} here. It's pretty {var2}. {var1} stuff!".format(var1='lit', var2='nice')
#I can inject anything here. It's pretty nice. Lit stuff!

Formatted String Literals

Perhaps the most straightforward and intuitive way are the newly introduced f-strings.

age = 34
print(f"He is {age} years old")
#He is 34 years old

F-strings let you inject outside variables directly into strings. They also read cleanly and directly.

I hope this has been a helpful introduction to string interpolation in Python! Check out the below links for more info.