python replace backslashes to slashes

杀马特。学长 韩版系。学妹 提交于 2019-12-29 08:30:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!