Take the 2-minute tour ×

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

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

share|improve this question
add comment

2 Answers

You can use the string .replace() method.

>>> print r'pictures\12761_1.jpg'.replace("\\", "/")
share|improve this answer
add comment

You can also use split/join:

print "/".join(r'pictures\12761_1.jpg'.split("\\"))


The other way you may use is to prepare data during it's retrieving(e.g. the idea is to update string before assign to variable) - for example:

f = open('c:\\tst.txt', "r")
print f.readline().replace('\\','/')

share|improve this answer
Did you read my question? I wrote that I know about r'pictures\12761_1.jpg'.split("\\") But how can I escape backslash if I already have variable with 'pictures\12761_1.jpg' value? –  Vyalov V. Jun 8 '11 at 8:16
Sorry if i missed this - but where you wrote this? –  Artsiom Rudzenka Jun 8 '11 at 8:19
I have tried the same without raw - e.g. typed in Python2.6 console the following: print "/".join('pictures\12761_1.jpg'.split("\\")) and it still works the same way. Or i miss something? –  Artsiom Rudzenka Jun 8 '11 at 8:26
If you try it in Python2.6 console you will see 'picturesW61_1.jpg' –  Vyalov V. Jun 8 '11 at 8:33
@Artsiom Rudzenka "I know about raw string" - sorry if thaw was not unclear. –  Vyalov V. Jun 8 '11 at 8:38
show 1 more comment

Your Answer


