Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace backslashes to slashes

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?

like image 563
Vyalov V. Avatar asked Jun 08 '11 07:06

Vyalov V.


1 Answers

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.

like image 57
Jeremy Avatar answered Nov 09 '22 03:11

Jeremy