Search code examples
python-3.xstringreplacepathescaping

Replace ('\\' , '/') in URLs problem when escape sequences are in the strings


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


Solution

  • 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