I thought it is a simple problem, I searched a lot but nothing suitable found! How to get rid of "Escape Sequences" in the strings when replacing '\' with '/' in python? I need to convert Windows Path to Unix Path but for example 'blahblah\nblahblah' or 'blahblah\bblahblah' make problems!
addressURL = "B:\shot_001\cache\nt_02.abc"
addressURL = addressURL.replace('\\','/')
print(addressURL)
# Result: B:/shot_001/cache
t_02.abc #
I also used os.path module but the results were the same!
Anyway I need to convert "B:\shot_001\cache\nt_02.abc" to "B:/shot_001/cache/nt_02.abc"
Thanks
CodePudding user response:
If all you want to do is convert:
"B:\shot_001\cache\nt_02.abc"
...to:
"B:/shot_001/cache/nt_02.abc"
...you can try this:
string = r"B:\shot_001\cache\nt_02.abc"
new_string = '/'.join(string.split('\\'))
NOTE: it's important to place the r
in front of the string - this denotes the string as a "raw string", and helps join
treat the special \n
as any other text, instead of as a carriage return. Find out more about raw strings here.
If you're looking for a better way to handle paths in general, I suggest you look up pathlib
: pathlib docs
If you were given a string that didn't start off "Raw":
This took a few tries...
s1 = 'B:\shot_001\cache\nt_02.abc'
s1 = repr(s1)[1:-1]
s2 = [each for each in (s1).split("\\") if each]
s2 = '/'.join(s2)
print (s2)
This produces:
B:/shot_001/cache/nt_02.abc
This drew on guidance from here.
CodePudding user response:
This is the best solution that I have found on the net( Thanks to the anonymous writer). This problem was not as easy as I thought:
import os
import re
def slashPath(path):
"""
param: str file path
return: str file path with "\\" replaced by '/'
"""
path = rawString(path)
raw_path = r"{}".format(path)
separator = os.path.normpath("/")
changeSlash = lambda x: '/'.join(x.split(separator))
if raw_path.startswith('\\'):
return '/' changeSlash(raw_path)
else:
return changeSlash(raw_path)
def rawString(strVar):
"""Returns a raw string representation of strVar.
Will replace '\\' with '/'
:param: str String to change to raw
"""
if type(strVar) is str:
strVarRaw = r'%s' % strVar
new_string=''
escape_dict={'\a':r'\a', '\b':r'\b', '\c':r'\c', '\f':r'\f', '\n':r'\n',
'\r':r'\r', '\t':r'\t', '\v':r'\v', '\'':r'\'', '\"':r'\"',
'\0':r'\0', '\1':r'\1', '\2':r'\2', '\3':r'\3', '\4':r'\4',
'\5':r'\5', '\6':r'\6', '\7':r'\7', '\8':r'\8', '\9':r'\9'}
for char in strVarRaw:
try: new_string =escape_dict[char]
except KeyError: new_string =char
return new_string
else:
return strVar
#--------- JUST FOR RUN -----------
s1 = 'cache\bt_02.abc'
print(slashPath(s1))
#result = cache/bt_02.abc