1

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

2 Answers2

1

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.

Vin
  • 929
  • 1
  • 7
  • 14
  • Thanks for your answer. How do i make the "string" raw when i get the strings as an output of a method? Imagine I have a list of paths and i can't use 'r' prefix manually to be honest I couldn't use it like for eg: r + string[i] – Milad Hatam Nov 08 '22 at 09:24
  • btw, i should write this script for python 2.7 and 3.9 . Unfortunately pathlib is not in python 2.7 – Milad Hatam Nov 08 '22 at 09:26
  • Interesting - sounds like you might get some guidance on this here: https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python – Vin Nov 08 '22 at 09:30
  • Ah - found a solution here: https://www.pythontutorial.net/python-basics/python-raw-strings/#:~:text=In%20Python%2C%20when%20you%20prefix,(%20%5C%20)%20as%20literal%20characters. Updating answer to reflect. – Vin Nov 08 '22 at 09:38
  • OK it took a few tries, but I think I've got it right now. You could just do it with: s2 = '/'.join([each for each in repr(s1)[1:-1].split("\\") if each]) but there's an awful lot going on there. Does this do what you wanted? – Vin Nov 08 '22 at 10:36
  • You nailed it Vineet, worked. Thanks for your kindness. – Milad Hatam Nov 08 '22 at 10:42
  • 1
    I tested it with all esc seq. I don't know why it has problem with \b ! e.g: "B:\shot_001\cache\bt_02.abc" become B:/shot_001/cache/x08t_02.abc – Milad Hatam Nov 08 '22 at 11:31
  • OK this has become obsessively interesting to me. Thinking about it for a few hours, I reckon the answer might lie in asking how you're going to get a method to return a string with '\b' in it... any method that returns a string whose __repr__() includes '\b' would have had to put a '\\' in, or construct the string as an r''. Otherwise the string (once created by the method) would not HAVE a '\b' in it, do you know what I mean? Can you get a method to produce such a string? – Vin Nov 08 '22 at 19:47
  • I wondered too. It's more complicated than what i thought! I have found a bunch of code that give us what it should be. I'm gonna paste it here. btw Thanks for your support, Vineet. – Milad Hatam Nov 08 '22 at 20:26
0

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