python replace backslashes to slashes
How can I escape the backslashes in the str开发者_C百科ing: '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?
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.
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'
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
精彩评论