Process Escape Sequences in a String in Python



The escape sequences are the special characters that are used to represent the whitespace characters, quotes, backslashes or non-printable characters within the string. These sequences start with the backslash followed by the character, For example \n result in newline.

However, in some cases we will come across the situations to process or even to ignore these situations. In this article we will learn how to process the escape sequences.

Example

Let's look at the following example, where we are going to consider the basic approach to process the escape sequences.

str1 = "Hello\tEveryone\nWelcome to TutorialsPoint"
print(str1)

The output of the above program is as follows -

Hello	Everyone
Welcome to TutorialsPoint

Using Python replace() Method

The Python replace() method is used to replace all the occurrence of oen substing in a string with another substring.

In this approach, we are going to use the replace() method to convert the escape sequences written as raw text into their actual escape characters.

Syntax

Following is the syntax for Python replace() method -

str.replace(oldvalue, newvalue, count)

Example

Consider the following example, where we are going to use the replace() method and observing the output.

str1 = "Apple\nBall\tCat"
result = str1.replace("\n", "\n").replace("\t", "\t")
print(result)

The output of the above program is as follows -

Apple
Ball	Cat

Using Python encode() and decode() method

The Python encode() method is used to encode the string using the specified encoding.

Syntax

Following is the syntax for Python encode() method -

str.encode(encoding=encoding, errors=errors)

The Python decode() methodis used to decodes the string using the codec registered for its encoding.

Syntax

Following is the syntax for Python decode() method -

Str.decode(encoding='UTF-8',errors='strict')

Example

In the following example, we are going to use encode() and decode() methods to process the escape sequences.

str1 = "TutorialsPoit\nTP"
result = str1.encode().decode('unicode_escape')
print(result)

The following is the output of the above program -

TutorialsPoit
TP
Updated on: 2025-04-21T15:45:58+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements