Quotes and Formatting

Quotes mark the beginning and end of a string. There are several types of quotes in Python and they serve different purposes. You sould know each of the quote types and when to use them.

Reference

Here’s a table to help you remember what quote to use:

Name

Example

Use

Single Quote

'Hello, world!'

Good for general use.

Double Quote

"Hello, world!"

Good for general use.

Triple Quotes

'''Hello, world!''' """Hello, world!"""

Stronger than single or double quotes. You can have multiple lines inside them.

Format Strings

f'Hello, my name is {name}'f"Hello, my name is {name}"f'''Hello, my name is {name}'''f"""Hello, my name is {name}"""

Variable interpolation is convenient.You can use double or single or triple quotes too.

Raw Strings

r"Newline (\n) is literal"

Raw strings don’t change the text at all

Byte Strings

b'\xF0\x9F\x98\xB8'

Write strings in their lower level byte encoding.

Triple Quotes

The quotes we’ve used so far (" and ') have a key limitation: They are common in English which sometimes causes errors. Here’s an example of a common error using single quotes:

print('I couldn't find that file.')

Notice the funny changes in color? That’s the syntax highlighter telling you that something is wrong. Another limitation single and double quotes is that a string cannot span multiple lines. So this statement is also an error:

print("I do not love you except because I love you;
I go from loving to not loving you,")

The triple quote is three copies of either a double-quote character " or a single-quote character '. Triple quotes are great because it’s very rare to have three copies of a quote character in normal English (or any other language for that matter). Also, triple quoted strings can contain multiple lines.

print ("""
Some say the world will end in fire,
Some say in ice.
From what I’ve tasted of desire
I hold with those who favor fire.
But if it had to perish twice,
I think I know enough of hate
To say that for destruction ice
Is also great
And would suffice.
""")

Copy the Robert Frost poem above into the next cell:

[ ]:

Notice how the whole poem is just one string!

The f-String

Essential! The f-string is the most important thing you’ll learn this week!

An f-string is just adding an f to any of the types of strings you’ve already learned. For example:

print(f"Hello World")

What makes the f-string useful is that it does variable interpolation. That means you can name variables in the string:

what = "World"
print(f"Hello {what}")

Try typing the example code into the next cell.

[ ]:

What happens if you forget the ``f``? Variable interpolation saves a ton of time and effort by making it much more convenient to use variables and language together. In the practice from the last lesson you made a version of the Pablo Neruda poem where you could change “love” with any other word. Here’s a snippet of that code:

word = 'program'
print ("I do not", word, "you except because I", word, "you;")
print ("I go from " + word + "ing to not " + word + "ing you,")

You may have noticed that it adds a lot of extra work when you have variables intermingled with words becuase you have to start and stop quotes. The f-string makes that much simpler. Here’s how you could rewrite the poem using f-strings:

word = 'program'
print (f"I do not {word} you except because I {word} you;")
print (f"I go from {word}ing to not {word}ing you,")

Enter the example into the next cell:

The f-string gets its name from the word format and is discussed further in the next section.

Formatting

Python provides a way to mix variables into quoted strings. Almost every program will use formatting in some way because it makes for informative messages to the user. There are two ways that we’ll use in the class to format text. The format() function, which has existed since Python 3 (but was back-ported to Python 2) and the newer f-string which was introduced in Python 3.6.

But first, let’s talk about the dot.

Functions and the Dot Operator

The format() function has a different syntax than print(). The format() function operates on a string using the dot (.) operator. The picture shows how to use the format() function with a string.

The dot operator

Try the code in the picture using print() as shown in the example:

print("Hello {}".format("World"))
[ ]:

Most of the time when you use a function like format() you want to store the result into a variable so that you can use it later. Adding an equal sign (=) and the name of a variable accomplishes this as shown.

Assignment and the dot operator

Execute the example code from the picture and notice that the formatted string is assigned to the variable phrase.

[ ]:

Print ``phrase`` so you can see what is inside of it.

The format() Function

The format function operates on a string, called a template, that contains holes denoted by the {} characters. The template can contain any number of holes and holes can be located anywhere in the string. This example creates a template (named template) then uses the format function to fill in the hole.

template = "Hello, my name is {}"
print(template.format("Mike"))

Run the code in the next cell:

[ ]:

Add a new ``print()`` statement to print a nametag for yourself.

Here’s an example where format() fills in multiple holes in the template:

template = "My name is {} and my favorite color is {}"
print(template.format("Mike", "blue"))

Type in the example and change it to print your name and your favorite color.

[ ]:

Notice that the number of arguments matches the number of holes, It’s an error to provide too few arguments. This code will cause an exception:

template = "My name is {} and my favorite color is {}"
print(template.format("Mike"))

It’s okay to supply more arguments than holes (though it’s probably a mistake). Extra arguments are ignored. This code works fine but looks funny:

message = "Hello, my name is {} and I'm a {}"
message.format('Mike', 'programmer', 'and nerd')
[ ]:

Formatting vs. f-strings

An f-string is the easiest way to format a string. The f-string causes Python to do variable interpolation. That means you can embed the name of a variable directly into the string and Python will replace the name with the variable’s value. The difference between an f-string and a regular string is that an f-string has holes, similar to the format() holes, but the holes have a name. The name of the hole has to be a variable in your program. Here’s an example of a Mad Lib program implemented with the format() function.

verb = 'leap'
noun = 'chickens'
print ('I like to {} with {}.'.format(verb, noun))

Here’s the same program, but implemented with an f-string.

verb = 'run'
noun = 'chickens'
print (f'I like to {verb} with {noun}.')

Notice how when the f is before the quote character the string becomes an f-string. The f can appear before any of the quote characters (including triple quotes). You can reference the name of a variable inside of an f-string by placing its name inside of parens. Type in both examples.

[ ]:

Which one do you like better?

Advanced Formatting

The f-string is convenient and compact but the format() function is more flexible and powerful. The format funciton lets you choose, reorder and reuse the values that go in the holes.

Numbered Holes

A numbered hole is a format hole that has a number inside. For example {0} and {1}. A numbered hole refers to the corresponding argument to format(). The first argument is zero {0}. Numbered holes allow you to print arguments in any order:

print("{1} is {0}".format('down', 'up'))

Try the example. Confusing?

[ ]:

You can reuse numbered arguments as many times as you want. For example:

print("{0}, {0} and {1}".format('up', 'away'))

What does Superman say?

[ ]:

But, you cannot mix numbered and unnumbered holes. This is an error:

print("{1} is {}".format('down', 'up'))
[ ]:

Named Holes

Named holes work similary to the f-string. A named hole is just like the named hole in the f-string. For example, it looks like {holename}. However, variables in your program are not automatically placed into named holes like they are with f-strings. You have to connect them using a special kind of argument to format. This is a little complicated at first, but you’ll get used to it:

verb = 'run'
noun = 'chickens'
print ('I like to {word1} with {word2}.'.format(word1=verb, word2=noun))

Type in that example:

[ ]:

Do you see the connection between ``word1`` and ``verb``? In the example notice how the holes are named {word1} and {word2}. Values for those holes are assigned in the argument to the format function: word1=verb. That construct says, the hole called word1 gets the value inside of verb. This “glue” makes named holes a bit confusing for beginners.

Escaping the { and } Characters

Sometimes you need to put braces { and } into a format string, but the format string wants them. If you want the literals { and } to appear in your string double them up. For example:

print (f'This is left brace {{ this is right brace }}')
[ ]:

Here’s an example of when you would use the double brace to print correct CSS:

[ ]:
css_template = '''
body {{
    padding-top: {};
}}'''

print (css_template.format('1.5em'))

Backslash Escape

The backslash \ character changes the meaning of the character after it. For example, you can prevent a quote from ending the string:

[ ]:
print ('I can\'t do that Dave.')

The backslash character gives other characters a special meaning.

\t is the tab character:

[ ]:
print('\tOne Tab')
print('\t\tTwo Tabs')

\n is the newline character:

[ ]:
print('One\nTwo\nThree')

If you want a literal backslash you can escape the backslash with a backslash (\\):

[ ]:
print ("tab is \\t")
print ("newline is \\n")

The r-String

The r-string is a “raw” string. The r-string doesn’t do anything special with the backslash (\) character to simplify some tasks. In particular that means you can’t embed the newline character into an r-string. Look at the difference between the output of the next two cells.

[ ]:
print (r"""
tab is \t
newline is \n
""")

The b-String

A b-String is a byte string. A byte string is made of the ones and zeros that encode the characters that we can read as English. Byte strings become regular strings through a character encoding. That is discussed in Lesson 7. Here’s an example of a byte string:

[ ]:
b'\xF0\x9F\x98\xB8'

Byte strings are a special type:

[ ]:
type(b'\xF0\x9F\x98\xB8')

Byte strings are decoded in to regular strings:

[ ]:
b'\xF0\x9F\x98\xB8'.decode('utf-8')