Python String - Replace Forward Slash with Backward Slash


Python String - Replace Forward Slash with Backward Slash

To replace the Forward slash (/) with Backward slash (\) in Python, you can use string replace() method. Call replace method on the given string, and pass forward slash string "/", and backward slash string "\\" as arguments. Please note that we need to escape the backward slash character in the replacement string, therefore, two backward slashes.

Program to replace forward slash with backward slash

We are given a string value in variable x. We have to replace the forward slash character with the backward slash character in the string x using string replace() method.

Python Program

# Given string
x = "/path/to/something/"

# Replace forward slash with backward slash
result = x.replace('/', '\\')

print(result)

Output

\path\to\something\

Summary

In this tutorial of Python string tutorials, we learned how to replace the forward slash character with the backward slash character in the string, using string replace(), with examples.