Escaping characters in a string
What happens when you need a quote inside your string, e.g. the boy’s mother?
Try this (assumming you are using an interactive Python prompt. Otherwise assign it to a variable or print()
the string):
>>> 'the boy's mother'
The problem is that Python thinks that you are “closing” the string after the character y
, leaving a dangling ‘ after the r
that does not have a matching “closing” quote.
To fix the problem, you can escape the quote inside the string with a backslash (\
)
>>> 'the boy\'s mother'
or enclose your string with a different type of quote.
>>> "the boy's mother"
>>> '''the boy's mother'''
If you have a very long string and need to “break up” your string in your code for easier reading, you will need to escape each line with a backslash (\
).
>>> 'Never gonna give you up, \
... Never gonna let you down, \
... Never gonna run around and desert you.'
You should still end up with a single-line string.
If you need to keep the newline in your text (e.g. to print a poem), use triple quotes to create a string spanning multiple lines.
>>> '''Never gonna give you up,
... Never gonna let you down,
... Never gonna run around and desert you.
... '''
'\n'
represents a newline character.
You can always manually insert a new line with '\n'
. If you print
a \n
character, the terminal will display a new line.
>>> print("Never gonna give you up,\nNever gonna let you down,\nNever gonna run around and desert you.")
Here are some other common special characters (called escape characters) that you can use:
\t
: tab\\
: backslash\'
: single quote\"
: double quote
NOTE: Many programming languages (C, C++, Java) have a special character (
char
) type, usually enclosed with single quotes (e.g.'a', 'b', 'c'
. In these languages, char are different from strings, which are usually enclosed with double quotes (e.g. “a string”). Therefore, ‘a’ is different from “a”. In Python, there is nochar
data type. Instead, a character is a string of length 1.
Raw strings
In Python, raw strings (indicated by an r
before the start quote) ignore escape characters.
>>> print("Love\nthis.")
>>> print(r"Love\nthis.")
Unicode strings
In Python, unicode strings are prefixed with a u
.
>>> print(u"\u00dcnic\u00f6de")
Useful for representing special characters.
>>> print(u"\U0001f600")
Or a smiley emoji 😀 (only if your terminal supports it! It did not work on my Windows Command Prompt 😢)
Python 3 strings are actually unicode strings by default, so there is actually no need to prefix it with a u
.
>>> print("\u00dcnic\u00f6de")
>>> print("\U0001f600")