String Formatting

In this lesson, we will learn about formatting strings in Python

We'll cover the following...

String formatting (AKA substitution) is the topic of substituting values into a base string. Most of the time, you will be inserting strings within strings; however you will also find yourself inserting integers and floats into strings quite often as well. There are two different ways to accomplish this task. We’ll start with the old way of doing things and then move on to the new.

Ye Olde Way of Substituting Strings

The easiest way to learn how to do this is to see a few examples. So here we go:

Press + to interact
my_string = "I like %s" % "Python"
print(my_string) # 'I like Python'
var = "cookies"
newString = "I like %s" % var
print(newString) # 'I like cookies'
another_string = "I like %s and %s" % ("Python", var)
print(another_string) # 'I like Python and cookies'

As you’ve probably guessed, the %s is the important piece in the code above. It tells Python that you may be inserting text soon. If you follow the string with a percent sign and another string or variable, then Python will attempt to insert it into the string. You can insert multiple strings by putting multiple instances of %s inside your string. You’ll see that in the last example. Just note that when you insert more than one string, you have to enclose the strings ...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy