Search code examples
pythonpathlib

Python replace Double Backlash with Single Bcklash


I am trying to convert the window path in Pathlib to string.

However, I can't convert the \\ to \

The code I ran

    fileDir = pathlib.Path(self.CURRENTDATAPATH)
    fileExt = r"*.xlsx"
    
    for item in list(pathlib.Path(fileDir).glob(fileExt)):
        self.XLSXLIST.append( str(item).replace( '\\\\', "\\") )

Got the result:

['D:\\data\\test.xlsx']

I would like to get this result

['D:\data\test.xlsx']

Solution

  • Backslash is used to escape special character in string. To escape a backslash you should use another backslash infront of it '\\'

    When contructing string, you can use a leading r symbol before the raw string to avoid escaping.

    print(r'\a\b\c')
    

    the output is

    \a\b\c
    

    The echo output will always display in the escaped style, but this will not effect your use.

    # echo of string s=r'\a\b\c'
    '\\a\\b\\c'
    

    So, your code is running as you wish, and the output is correct, just with another displaying format.