问题
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?
回答1:
You can use the string .replace()
method.
>>> print r'pictures\12761_1.jpg'.replace("\\", "/")
pictures/12761_1.jpg
回答2:
You can also use split/join:
print "/".join(r'pictures\12761_1.jpg'.split("\\"))
EDITED:
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('\\','/')
>>>'pictures/12761_1.jpg\n'
来源:https://stackoverflow.com/questions/6275695/python-replace-backslashes-to-slashes