Escape Characters

In Python, escape characters are backslash \ followed by the character you want to insert. This special sequence allows you to include particular string values that wouldn’t be possible to write directly.

Common Escape Characters

Here are some common escape characters used in Python:

  1. \n : Inserts a newline in the text at that point.
  2. \t : Inserts a tab in the text at that point.
  3. \\ : Inserts a backslash character in the text at that point.
  4. \" : Inserts a double quote character in the text at that point.
  5. \' : Inserts a single quote character in the text at that point.

Let’s see these escape characters in action with some examples.

 1# Use of \n
 2print("Hello\nWorld")
 3
 4# Use of \t
 5print("Hello\tWorld")
 6
 7# Use of \\
 8print("Hello\\World")
 9
10# Use of \"
11print("Hello\"World")
12
13# Use of \'
14print('Hello\'World')

Running the above code outputs:

Hello
World
Hello	World
Hello\World
Hello"World
Hello'World

Raw Strings

Sometimes you might want to ignore the escape sequences in a string. This can be done using raw strings. Simply prefix your string with a r or R.

1# Without raw string
2print("C:\\user\\name")
3
4# With raw string
5print(r"C:\\user\\name")

In the first print statement, \n is treated as a newline. However, in the second print statement, it’s treated as the literal characters ‘' and ’n’.

Running the above code outputs:

C:\user
ame
C:\\user\\name

Note

The backslash \ followed by any character that doesn’t form a recognisable escape sequence results in a syntax error. Therefore, to include a literal backslash in a string, always escape it using \\.