Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What are escape characters in Python?

Sarah Tanveer

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.

Example code:

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 character
print('I'm writing code')

Let’s print the same thing using an escape sequence:

# adding the escape sequence removes the error
print('I\'m writing code')

# we can also print other special characters such as the
# escape sequence itself
print("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 t
print("Printing the letter t to test")

# using escape seq
print("Printing the letter \t to test")

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring