Replace Forward Slash With Backslash in Python

Contents:

A forward-slash (/) in a Python string can be replaced by a backslash (\) using the String replace() function, translate() method, or regular expression(re.sub()).

Using replace()

example_string = "path/to/check"
new_string = example_string.replace("/", "\\")
print(new_string)


Output:

path\to\check

Using translate() function

stringn = "book/pencil/ink/pen/rubber"
stringn1 = stringn.translate(str.maketrans({'/': '\\'}))
print(stringn1)


Output:

book\pencil\ink\pen\rubber

Using regular expression (re.sub())

import re
string1 = "path/to/check/and/edit"
string2 = re.sub("/", r"\\", string1)
print(string2)


Output:

path\to\check\and\edit

To get more details about those concepts, continue reading on. There is more to learn. First of all, let’s discuss backslash.

Backslash in Python

In Python, the backslash is a special character.  First of all, it is used as part of a special character sequence; for example, “\n” means move to the next line, “\b” is the backspace character, and “\t” is tab space in Python code. In these cases, Python considers the sequence of characters as a single character in each case.

Secondly, a backslash can be used as an escape character – in this case, when a backslash is placed in front of a particular character, it changes the meaning of that character. In fact, backslash in Python is represented as “\\”.

print("\")

Output: syntax error: unterminated string literal

print("\\")

Output:

\

In the first print statement, the backslash changes the meaning of the second quotation from being a closing quotation to being a literal string character hence the error “unterminated string literal”. Therefore, print(“example\”string”) will output example”string because the second quotation marks have been rendered literal string character by the escape character -the backslash.

Once the concept of representing backslash in Python is clear, we can now discuss how to replace forward-slash with a backslash.

Method 1: Using the inbuilt String replace() function

The general syntax for replace() function is:

example_string.replace(old_substring, new_substring, count)

Where count is an optional argument representing the number of occurrences of the old_substring to be replaced. By default, the function replaces all occurrences of the given substring.

example_string = "Python/programming/language"
new_string = example_string.replace("/", "\\")
print(new_string)


Output:

Python\programming\language

Note: replace() string returns a copy of the string after making the replacement, and therefore, the example_string variable will still have the original string even after execution.

Method 2: Using translate() function in Python

The translate() function allows one to replace one or multiple characters which should be provided in a dictionary as shown below. The code replaces forward-slash (/) and “e” in a string with a backslash.

stringn = "book/pencil/ink/pen/rubber"
stringn1 = stringn.translate(str.maketrans({'/': '\\', "e": "\\"}))
print(stringn1)


Output:

book\p\ncil\ink\p\n\rubb\r

Note that the keys for the translate dictionary must be a single character otherwise, you will run into an error.

Method 3: Using regular expression (re.sub()) in Python

As the name suggests, the pre-installed re package works with regular expressions to detect patterns in strings. The package has a function sub() that can be used to find and substitute substrings. For example,

import re
string1 = "Python/programming/language/3.10"
string2 = re.sub("/", "\\\\", string1)
print(string2)


Output:

Python\programming\language\3.10

In the re module, we need to pass “\\\\” as the pattern to capture a single backslash.

Reason: In the package, the backslash is also used as an escape character, and therefore, we need to pass “\\”, and since we also need “\\” for a Python literal string, then a valid pattern for a backslash is “\\\\”.

Alternatively, we can use raw string formatting (they are strings preceded by r), which converts backslash into a literal string. Note that, in the code, we still use “\\”, because the raw string only applies to the re pattern but we still need to write backslash as “\\”

import re
string1 = "Python/programming/language/3.10"
string2 = re.sub("/", r"\\", string1)
print(string2)


Output:

Python\programming\language\3.10