
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I un-escape a backslash-escaped string in Python?
In Python, the backslash-escaped string contains the characters that are followed by backslash(\), which are used as escape characters.
For example, \n represents the literal characters "" and "n" (not a new line). In some scenarios, we need to unescape such a string, i.e, convert these sequences back to their intended special characters or read them as normal text.
Python provides several ways to achieve this. In this article, we will explore how to un-escape a backslash-escaped string.
Using Python .decode() Method
The Python decode() method is used to decode the string using the codec registered for its encoding. In this approach, we are going to use the decode() function to read the escape sequences and skip/ignore them.
Syntax
Following is the syntax for the Python decode() method -
str(x)Str.decode(encoding='UTF-8',errors='strict')
Example
Let's look at the following example, where we are going to use the str() function for concatenating a string with a number.
str1 = "Welcome To\nTutorialsPoint" result = str1.encode().decode('unicode_escape') print(result)
The output of the above program is as follows -
Welcome To TutorialsPoint
Using Python codecs Module
The second approach is by using the codec module. Where we are going to use the codec.decode() to decode the escape sequences in the string, similar to the decode() method.
The Python codec module provides the interface for encoding and decoding data, especially for working with text files in different character encodings.
Example
Consider the following example, where we are going to use the codec.decode() method.
import codecs str1 = "Hi\nHello\tVanakam" result = codecs.decode(str1, 'unicode_escape') print(result)
The following is the output of the above program -
Hi Hello Vanakam
Using python literal_eval() Method
The Python literal_eval() method is provided by the Python Abstract Syntax Trees module, which is used to evaluate a string that contains a valid Python literal expression, such as numbers, strings, Boolean, etc.
We can use the ast.literal_eval() method to evaluate the string as a Python literal. It treats the input string as the literal and analyzes the escape sequences.
Example
In the following example, we are going to use the ast.literal_eval() method to evaluate the string as a Python literal.
import ast str1 = "'Ciaz\nCruze'" result = ast.literal_eval(str1) print(result)
The output of the above program is as follows -
Ciaz Cruze