Python String – Escape Characters


Escape Character

Use the escape character when we want to add a character to a string that python doesn’t accept. Example, single quote(‘), double quote(“), backslash(), etc. They are known as escape character because they allow us to avoid the special meaning of the characters.

For example : John replied “I’m good.”

We won’t be able to print this line using a print statement because it has both a single and double quote. We use escape characters to print these characters.

Use of backslash

Python String - Escape Characters

In Python, backslash(‘\’) is used as the escape character. It is used as a prefix with the character we want to insert in the string. When a backslash is followed by a specific character, it indicates that the character following the backslash should be treated differently than its literal value. This process is also known as “escaping.”

We get SyntaxError trying to print the below line:

In [1]:
print("John replied "I'm good."")
  File "<ipython-input-1-c2d83d97b40f>", line 1
    print("John replied "I'm good."")
                         ^
SyntaxError: invalid syntax

We used the escape character to print double quotes(“).

In [2]:
print("John replied \"I'm good.\"")
John replied "I'm good."

Escape Sequences

There are certain characters that start with backslash(\), have some specific task to do. These are the non-printable characters and are interpreted in different way by the interpreter. These character constraints are known as escape sequences. Again, they are known as escape sequences because they are used to escaping from the normal way the characters are displayed.

For Example, ‘/n’, which means new line, is the most common escape sequence. It is used to jump to the next line.

Some of the available escape sequences are:

Escape Sequence Output
\n New Line
\\ Backslash
\’ Single Quote
\” Double Quote
\t Tab
\b Backspace
\r Carriage Return
\v Vertical Tab

Few Examples

Few most useful escape characters are:

  1. Newline (\n): The newline escape sequence is used to insert a new line in a string. When encountered, it moves the cursor to the beginning of the next line.
  2. Tab (\t): The tab escape sequence inserts a horizontal tab in a string.
  3. Backslash (\): To include a literal backslash in a string, you use the double backslash escape sequence.
  4. Quotation Marks (\” or \’): Escaping quotation marks allows you to include them in a string without prematurely ending the string.

New line (\n).

In [1]:
print("Hello \nWorld")
Hello 
World

Tab (\t).

In [2]:
print("Hello \tWorld")
Hello 	World

Backslash (\\).

In [3]:
print("Hello \\ World")
Hello \ World

Quotation Marks (\” or \’).

In [4]:
print("Hello \" World")
print("Hello \' World")
Hello " World
Hello ' World

Preventing Escape Sequence Interpretation

Preventing Escape Sequence Interpretation

Sometimes we may need to avoid the default behaviour of the escape sequence. For example, we may like to print \n in the string itself. Three ways to achieve this are:

1. Doubling backslash

An additional backslash (\) is used with the escape sequence to prevent its default interpretation.

In [1]:
print("Use \\n for new line.")
Use \n for new line.

2. Raw String

Here, we use capital R or small r to prevent its default interpretation. We just have to prefix the string with a capital R or small r, it will automatically do the task. We need not to manually do anything in this case.

In [1]:
print(r"Use \n for new line.")
Use \n for new line.

3. Using repr() function

The repr() function also works in the same way as raw string. It will not interpret the escape sequence and return the object as it is in its printable format. We simply have to pass the string to the repl() function.

In [1]:
print(repr("Use \n for new line."))
'Use \n for new line.'

Use Cases

  1. Consider scenarios where you need to include a path in a string. Escape characters make it possible to handle such situations without causing errors or unintended behaviour.
  2. When dealing with user input in a form, escape sequences enable developers to validate and process input containing special characters without causing unintended effects in the program.

References:

  1. Preventing escape sequence interpretation
  2. Escape Character
  3. Escape Sequences