7. Which Quotes to Use When Creating Strings

Quick Overview of Day

Triple quoted strings can span multiple lines, and contain other types of quotes. Work on a Python assignment, focused on input/output of strings, and conditionals.

7.1. A Bit More Detail About Strings

Strings in Python can be enclosed in either single quotes (') or double quotes (" - the double quote character), or three of the same separate quote characters (''' or """).

Double quoted strings can contain single quotes inside them, as in "Bruce's beard", and single quoted strings can have double quotes inside them, as in 'The knights who say "Ni!"'. Strings enclosed with three occurrences of either quote symbol are called triple quoted strings. They can contain either single or double quotes:

Triple quoted strings can even span multiple lines:

Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround your strings. Once it has parsed the text of your program or command, the way it stores the value is identical in all cases, and the surrounding quotes are not part of the value.

7.2. What Does This Program Do?


Your teacher may choose to use the following examples as a class activity, by displaying the examples, and having you take a guess as to what you think each will do before running the code.

What will the following programs output? Why?

Can you fix the error in the following programs?

7.3. f-strings

Another alternative to concatenating strings together is to use f-strings (formatted string literals). An f-string allows you to easily create a string that has the value of variables inserted into it. To create an f-string, you simply put the letter f before the quotes that begin the string. This tells Python that it should look for variable names inside the string, and if it finds any, it will replace them with the value of that variable. For Python to find the variable, you must enclose the variable inside curly brackets, like {some_variable}. Consider this example of using an f-string:

You can also use triple quoted strings in combination with f-strings to create multi-line strings, as shown below:

7.4. Assignment Work Time

Please spend the rest of the class continuing to work on your current Python assignment (likely something emphasizing user input and output).

Next Section - 8. The while Statement