Escape sequences in Python


An escape sequence or escape character allows you to insert a special character in a string. For example, you can insert a new line in a string using \n character.

The backslash \ is used before the character that you want to escape.

List of escape characters in Python

The following table shows you a list of escape characters or sequences in Python –

Usage of escape sequence in Python with examples

A string is a collection of characters inside the single or double quote. Now, what if you want to insert single or double quotes in a string?

Using single or double quotes in a string

You can use single quotes inside the string enclosed with double-quotes or double quotes inside the string enclosed in single quotes.

For example –

print("Hey, I'm Lalit")
print('This is a "Hello World!" program in Python')

This will print the strings like given in the image –


But using single quotes inside a string enclosed with single quotes or double quotes inside the string enclosed with double quotes are not allowed this will give you a syntax error.

print('Hey, I'm Lalit')
print("This is a "Hello World!" program in Python")

Here both the statements are wrong and will through the syntax error in Python.

Including backslash in a string

If you want to include a backslash character in a string you need to escape it with a backslash. For example, to print the path of a directory on Windows you will need to use backslash every time you insert a backslash in the string.

Example –

print("C:\\Users\\lalit\\Downloads")

This will print the path with the single backslashes –

Inserting a new line

You can insert a new line by using the \n character in a string. For example –

print("You can create a multiline string \nby using escape sequence in Python")

You can see the output in the image below.

You can use \n multiple times to insert multiple newlines.

Similarly, you can use other escape sequences that are given in the above table.

Python raw string

Python raw string treats backslash character as literal instead of treating it as an escape character. You can create a raw string by prefixing it with r or R.

print(r" Hello \ World!")

This will print the string with the backslash character. Another example is –

print(r" Hello \n World!")

The string will be treated as normal text so instead of inserting a new line, this will print the\n with the string.

But using a backslash at the end of a raw string will through an error.

Ok, that’s all for now. I hope this article given you a basic idea of escape sequences used in the Python programming language.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.