Single Quotes versus Double Quotes¶
As mentioned above, we can also use single quotes when defining a string. The following definition of my_string
is equivalent to the previous definition.
my_string = 'Hello world!'
print(my_string)
Hello world!
One benefit of being able to use either single quotes or double quotes when creating strings is that it allows us a convenient way to create strings that themselves contain quotes as characters. For instance, assume that we want to create a variable containing the following string:
He yelled, "I have had enough!" before storming out of the room.
The following attempt at creating this string will give us an error.
sentence = "He yelled, "I have had enough!" before storming out of the room."
File "<ipython-input-2-4965ff137a3f>", line 1
sentence = "He yelled, "I have had enough!" before storming out of the room."
^
SyntaxError: invalid syntax
In the example above, Python got confused by the quotation marks in the middle of the string. When it encountered the second quotation mark, it believed that this was the end of the string, although this was intended to be part of the string.
There are a few ways to fix this. The simplest is to use single quotes to define the string. When Python encounters the first single quote, it knows that a string is being defined. It won’t stop reading characters into the string until it hits another single quote. Any double quotes that it encounters along the way will be treated as inert characters.
sentence = 'He yelled, "I have had enough!" before storming out of the room.'
print(sentence)