How to Escape Sequence in Python

In this Python tutorial, I will show you how to escape sequences in Python.

While building the text editor application in Python, I implemented the functionality that used the escape sequence to insert characters into a string. For some characters, like a single quote, space, etc., I used the backslash to insert these characters into the string.

In this tutorial from Sractch, I have explained the escape sequence and why it is used. Additionally, I have shown some examples of how to use it.

What does an escape sequence in Python mean?

The escape sequence is a sequence of characters treated as special when the Python interpreter encounters it in the string literal.

But how Python knows it is an escape sequence, so the escape sequence is represented using the backslash (‘\’) followed by the character.

You can’t insert some characters into the Python string directly; these are called illegal characters.

For example, if you try to insert a single quote within the string, python raises an error because it doesn’t correctly interpret it in a string. Execute the code below.

task = 'I wake at 2 o'clock'
print(task)
Error of Escape Sequence in Python

When you try to store the string ‘I wake at 2 o’clock’, it shows a syntax error; if you look at this string, it contains a single quote at 2 o’clock.

Also, you can see that the string is wrapped using a single quote, ‘I wake at 2 o’clock’ so the interpreter is confused about which single quote is the end of the string.

READ:  How to Split a Sentence into a List of Words in Python

So, how to fix that, the solution is to use the single quote within the string wherever you want to use the backslash (‘\’) before that single quote is shown in the code below.

task = 'I wake at 2 o\'clock'
print(task)
What does an escape sequence in Python mean

Now, look at the output. This time, it inserts the single quote using the backslash; this is how you can escape the sequence.

There are different types of escape sequences, which are shown below.

Escape SequenceDescription
\\Backslash (\)
\'Single quote (')
\"Double quote (")
\nNewline
\tTab
\rCarriage return
\bBackspace
\fForm feed
\oooThe character with the octal value ‘ooo’
\xhhThe character with hex value hh

From the above table, you will now know the type of escape sequence. Let’s take examples.

Escape Sequence For Space in Python

To insert the space between strings, you can use Python escape space, represented using ‘\t’, called the horizontal tab.

For example, if you have data entries and want to separate them by tabs for better readability, use the ‘\t’.

For example, print the following entries as shown in the code.

print("Section 1:2023 Sales Data")
Before Python Escape Space in String

Look at the output; the entire is not very readable. Suppose you must insert space between the semicolon (:) and 2023 Sales Data. Then, you can use ‘\t’ as shown in the code below.

print("Section 1:\t2023 Sales Data")
Python Escape Space

Now you can see that the ‘\t’ inserted the space in the string, which enhances the readability of the entry.

Let’s take one more example containing more than one entry using the code below.

print("Section 1:\t2023 Sales Data")
print("Section 2:\t2023 Expense Data")
print("Section 3:\t2023 Product Sale Data")
Escape Sequence For Space in Python

This is how to insert the space in the string using the Python escape space sequence called horizontal tab ‘\t’.

READ:  How to Convert Bool to Int in Python

Escape sequence backspace in Python

The escape sequence backspace is represented by ‘\b’; it is used to remove or delete the space between strings.

For example, if you have a string like ‘PythonPythonguides’, now execute the code.

print( 'PythonPythonguides')
Escape sequence backspace in Python Example

Look, the string is not correct. It should be only ‘Pythonguides’, but it is like ‘PythonPythonguides’. To remove the first word, ‘Python’, you can use the backspace ‘\b’ as shown in the code below.

Count the number of characters you want to remove or return; here, the word python is consistent with 6 characters, so specify the backspace ‘\b’ six times after the word ‘Python’ as shown in the code below.

print( 'Python\b\b\b\b\b\bPythonguides')
Escape sequence backspace in Python

Look, it removes the word ‘Python’ from the ‘PythonPythonguides’. Here, backspace removes the space from the right to left direction. As its name implies, it is backspace, which eliminates the space in the back direction, according to me.

This is how to escape sequence backspace in Python using the ‘\b’.

Escape Sequence Form Feed in Python

The escape sequence for feed is represented by ‘\f’. The form feed is invisible characters inserted in the string; you might not see this, and the text editors use this. This form feed is called page-breaking control characters or page separators.

It moves the cursor to the downward page. For example, suppose you have to add the logical page break in text files.

Suppose you store the printed reports in a text file; here, you must use the form feed characters to indicate the page’s end and another page’s start. To do so, execute the code below and understand it.

report = "2024 Sales Report\n-----------------\nJanuary: $5000\nFebruary: $6000\fMarch: $7000\nApril: $8000\n\fSummary: Sales are increasing."
with open("sales_report.txt", "w") as file:
	file.write(report)
Escape Sequence Form Feed in Python

When you execute the above code, it creates a new file called sales_report.text in your directory, and the report is written to it, which you can see in the above output.

READ:  How to Iterate through a Dictionary in Python with Index? [4 Methods]

The right side contains a file containing all the report data. The form feed, represented by the small red rectangle FF, is also visible.

The form feed is not visible in the text file, but I have shown how it looks for your understanding.

Conclusion

In this Python tutorial, you learned how to escape sequences in Python.

Where you learned to escape characters in the string, the backslash is used before that character. Additionally, you learned about different types of escape sequences, such as single quotes (‘\”), tabs (‘\t’), and form feeds (‘\f’).

You may like to read: