Today we’ll be talking about escape sequences.
Escape characters / sequences are characters used to escape the special meaning of another character.
We use the backslash (\) character to escape characters.
Escape sequences:
\n | new line |
This sequence is used for a new line:
>>> a = "Let's break the line \nright here"
>>> print(a)
Let's break the line
right here
Escape characters don’t work if we echo strings:
>>> a
"Let's break the line \nright here"
\t | horizontal tab |
This sequence adds tabs:
>>> a = "We need more \t\t\t\t\t\t\t tabs!"
>>> print(a)
We need more tabs!
\\ | backslash |
This sequence should be used if you need a single backslash.
>>> a = "I need a single \\ here."
>>> print(a)
I need a single \ here.
If you need a double one, just add one more:
>>> a = "I need a double \\\ here."
>>> print(a)
I need a double \\ here.
\’ | single quote |
This sequence is used for a single quote:
>>> a = '"How about a single \'?", he asked.'
>>> print(a)
"How about a single '?", he asked.
\” | double quote |
And this sequence is used for a double quote:
>>> a = "Double \" seems right."
>>> print(a)
Double " seems right.
\uxxxx | Unicode character with 16-bit hex value xxxx |
This sequence can be used for Unicode characters.
>>> a = "The first letter is \u0041."
>>> print(a)
The first letter is A.
This is particularly useful for characters from other alphabets. You can find the Unicode code points online. For example let’s take this code point: U+19EC:
>>> a = "What does \u19ec mean?"
>>> print(a)
What does ᧬ mean?
or this one: U+231A for the symbol of a watch:
>>> a = "Watch your \u231a!"
>>> print(a)
Watch your ⌚!
Here’s the video version of this article: