Lesson 2 - Introduction to Strings

In Python, there are many ways to represent text with strings, in order to handle things like apostrophes, quotation marks, and multiple lines.

You can assign a string value to a variable using double quotes. Execute the cell below (press Shift-Enter in the cell) to assign a string value to the variable message. Then use the next cell to print the value of message.

Double Quotes


In [ ]:
message = "Meet me tonight."

In [ ]:
print(message)

Note that the print command above doesn't use quotes. What do you think the cell below will print? Run it to see what happens. There will be more about this later, but the print function accepts variables and literals.


In [ ]:
print("message")

Single Quotes

You can also put a string inside single quotes.


In [ ]:
message2 = 'Type your own message here.'

After you run the cell above to assign your message to message2, enter a Python command below to print the value of message2 and then execute it.


In [ ]:

Quoting Quotes

Why does Python allow both double and single quotes? Execute the following cell to see what can go wrong with using single quotes.


In [ ]:
message3 = 'I'm looking for someone to share in an adventure.'

The Python interpreter thinks the apostrophe in I'm is the end quote, and it can't understand the rest of the line, so it gives a syntax error starting right after the second quote.

Escape character \

One way you can fix the error by adding a backslash \ before the apostrophe you want to print. The backslash is called an "escape character" and tells Python to accept the next character as part of the string. Add a backslash before the apostrophe in I'm to fix the code below, then check it with the print statement.


In [ ]:
message3 = 'I\'m looking for someone to share in an adventure.'

In [ ]:
print(message3)

Quotes in Quotes

But, thanks to the fact that Python also allows double quotes, the more elegant way to include apostrophes in your string is to enclose the whole string in double quotes. Try using double quotes to fix the line below.

Jupyter Note: Jupyter will automatically close your quotes for you as you type, so you will need to delete any extra quotes that you don't want. Autoclose is a Jupyter feature that can be turned off, but we'll just have to deal with it now!


In [ ]:
message3 = 'I'm looking for someone to share in an adventure.'

In [ ]:
print(message3)

Triple Quotes

More complex quoting requirements can be handled with triple quotes. You can quote single and double quotes as well as line feeds with triple quotes. Here's an example...


In [ ]:
movie_quote = """One of my favorite lines from The Godfather is:
"I'm gong to make him an offer he can't refuse."
Do you know who said this?"""

In [ ]:
print(movie_quote)

In [ ]:
print("socratica".upper())  # Just playing around - strings have methods

In [ ]: