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?
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?
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:
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"
© 2022 - 2024 — McMap. All rights reserved.