python replace backslashes to slashes

Vyalov V. picture Vyalov V. · Jun 8, 2011 · Viewed 59.2k times · Source

How can I escape the backslashes in the string: 'pictures\12761_1.jpg'?

I know about raw string. How can I convert str to raw if I take 'pictures\12761_1.jpg' value from xml file for example?

Answer

Jeremy picture Jeremy · Jun 8, 2011

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

Python 2:

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

Python 3:

>>> print(r'pictures\12761_1.jpg'.replace("\\", "/"))
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.