python replace backslashes to slashes

2020-02-13 08:41发布

问题:

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'


回答3:

I know it is not what you asked exactly, but I think this will work better. Tit's better to just have the names of your directories and use os.path.join(directory,filename)

"os.path.join(path, *paths) Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component"

https://docs.python.org/2/library/os.path.html