python replace backslashes to slashes

You can use the string .replace() method along with rawstring.

Python 2:

>>> print r'pictures\12761_1.jpg'.replace("\\", "https://stackoverflow.com/")
pictures/12761_1.jpg

Python 3:

>>> print(r'pictures\12761_1.jpg'.replace("\\", "https://stackoverflow.com/"))
pictures/12761_1.jpg

There are two things to notice here:

  • Firstly to read the text as a drawstring by putting r before the
    string. If you don’t give that, there will be a Unicode error here.
  • And also that there were two backslashes given inside the replace method’s first argument. The reason for that is that backslash is a literal used with other letters to work as an escape sequence. Now you might wonder what is an escape sequence. So an escape sequence is a sequence of characters that doesn’t represent itself when used inside string literal or character. It is composed of two or more characters starting with a backslash. Like ‘\n’ represents a newline and similarly there are many. So to escape backslash itself which is usually an initiation of an escape sequence, we use another backslash to escape it.

I know the second part is bit confusing but I hope it made some sense.

Leave a Comment