Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Format Strings in Python


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.