In many programming languages, some characters serve different functions and so cannot be displayed or printed like other characters.
These characters are referred to as special characters. Some examples are double quotes ("), single quotes (’), etc.
To print these special characters, a backslash (\) is used. This black slash is called an escape sequence
.
Similarly, the escape sequence
can be used to make an otherwise printable character serve a special function. For example, the letter ‘n’ can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line.
First, let’s see what happens when we try to print a special character i.e., a single quote or an apostrophe:
# printing this is not possible bcz there is a special characterprint('I'm writing code')
Let’s print the same thing using an escape sequence
:
# adding the escape sequence removes the errorprint('I\'m writing code')# we can also print other special characters such as the# escape sequence itselfprint("The escape sequence in Python is: \\")
Now let’s use the escape sequence
to cause a character to serve another purpose. For example, the letter t
is printable but adding an escape sequence
to it will cause it to serve as a tab space.
# printing the letter tprint("Printing the letter t to test")# using escape seqprint("Printing the letter \t to test")