Working with Literals in Python - dummies

Working with Literals in Python

By Brendan Scott

In Hello World!, the message that print is sending is called a literal. Think of a literal as being something within single quotes. (Single quotes are this ‘ instead of double quotes, like this “).

Literals are the rocks (not rock stars) of the programming world. You can pick them up and throw them around, but you can’t change them. They can exist by themselves in a program, but they don’t do anything:

 >>> 'Hello World!'
 'Hello World!'

That’s a program that has only a literal and nothing else. It’s just a little bit different from the Hello World! program. In that program there were no quotes in the text that Python printed, but in this example the second line has single quote marks around it.

Python doesn’t judge the content of a literal. That means you can misspell it, fill it with weird words, and even fill it with weird, misspelled words. You still won’t get an error message from Python.

The single quotes are important. If you leave them out, Python thinks the text is telling it to do something. In this example, Python doesn’t know what Hello and World are supposed to do:

  >>> Hello World!
    File "<stdin>", line 1
      Hello World!
               ^
  SyntaxError: invalid syntax

The literals mentioned here are all string literals. String literals are read like text, instead of like a number.

You can make a sequence of characters into a string literal by putting a single quote on each side:

Hello World! → ‘Hello World!’

However, watch what happens when you make a literal from something that already has a single quote (like the word didnt):

  >>> 'didn't'
    File "<stdin>", line 1
      'didn't'
            ^
  SyntaxError: invalid syntax

Python reaches the second single quote and thinks that it marks the end of the string literal — but that’s not where you wanted it to end.

You can make a literal that includes a single quote by using double quotes around the outside of the literal. You can use double quotes any time, even if there isn’t a single quote involved.

   >>> "didn't"
   "didn&apos;t"
   >>> '"I have a very eely hovercraft," he said.'
   '"I have a very eely hovercraft," he said.'

Ways you can create string literals include such diverse elements as single quotes and double quotes. But that’s not all! You can also use triple single quotes and triple double quotes to create string literals. Seriously:

   >>> '''This is a literal made with triple single quotes.'''
   'This is a literal made with triple single quotes.'
   >>> ""This is a literal made with triple double quotes [sic].""
   'This is a literal made with triple double quotes [sic].'

Make sure you can create at least one literal that has a single quote, one that has a double quote, and one that has both a single quote and a double quote.