BackReturn Home

2 - Python Strings

← PreviousNext →





This lesson teaches how to:

• How to store a string inside a variable

Similar to how the term is used within mathematics, a variable is a way to represent a whole range of different things. For example, here is a bit of code...

message = "Meet me tonight."

In this case, the variable is message, and everything after the equals sign is what it represents. A string is simply a list of items, be they letters, numbers, or some other symbols. Everything within the quotation marks is considered a string. Therefore, we used the equals sign to make a variable named message that represents a string containing the sentence Meet me tonight.

To view the string within the Python console, print the variable:

print(message)

We should get...

Meet me tonight.

We can also use apostrophes to specify the contents of a string:

message2 = 'The clock strikes at midnight.'

If we want a string that has an apostrophe within it, then we must use quotation marks:

message3 = "I'm looking for someone to share in an adventure."

If we want a string that has quotation marks within it, then we must use apostrophes:

message4 = 'The phrase "Beam me up, Scotty" was never said on Star Trek.'

If we want a string that has a combination of apostrophes and quotation marks, then we must contain it within three apostrophes or three quotation marks:

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

If our string is long, then it may take up more than one line. This will be represented by three dots in front of each new line. It might look something like this:

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