# How to replace \ with in Python?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

There are two ways to go about replacing \ with \ or unescaping backslash escaped strings in Python. First is using literal_eval to evaluate the string. Note that in this method you need to surround the string in another layer of quotes. For example:

>>> import ast
>>> a = '"Hello,\\nworld"'
>>> print ast.literal_eval(a)
Hello,
world

Another way is to use the decode('string_escape') method from the string class. For example,

>>> print "Hello,\\nworld".decode('string_escape')
Hello,
world
Updated on 30-Sep-2019 08:23:04