Format Strings in Python

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet

Single quotes and double quotes can both be used to declare strings in Python. You can even use triple-double quotes! Learn when to use each in this lesson as well as variable substitution in strings.

In Python, we can do basic string declarations like name = Will. If there is a quote in there, we can start our string with double quotes, and that single apostrophe will be included as part of the string.

We can do multi-line strings as well. When you use multiline strings, the carriage returns are preserved, so that as you print those out, it's returned exactly as you typed it in.

There are different ways to escape characters as well. Take a look this. If I start my string with a single quote, and then I want to refer to Will's ball, I need to escape that, because this single quote would terminate the string.

I can escape it with the backslash character, or as you saw at the beginning of the lesson, I can use a double quote, and that single quote will be ignored. I can also use the triple quotes, and the single quote will be ignored as well. I can also include characters like the tab character, and that'll get interpreted whenever the string is parsed.

Let's take a look at how we can format some strings. We'll do item = ball, except that's a string, so I need to quote it as a string. We'll say the color = red. Now, I can say print, and pass in the substitution character here and here, and that's the end of my string.

Then I tell it the variables that I would like substituted in that string. Whenever it prints out, it prints out "Will's ball is red."

One other way you can do this is with the string's format operator or format method. I'll specify item0 and item1, terminate my string, and then use dot format, and pass in the variables I'd like substituted, so when it prints out, it prints out "Will's ball is red."

As you might expect, those are positional operators, so the number inside of the curly brackets there is the positional variable that you want specified.