0

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']
W Kenny
  • 1,855
  • 22
  • 33
  • 1
    Your list already contains exactly the data you want - you're just reading it wrong, because you're unfamiliar with `repr` and string literal escaping. The double backslashes are a product of the escaping involved in creating a valid string literal - the actual string contains single backslash characters. – user2357112 Nov 29 '20 at 07:29
  • 1
    The double backslash is an escaped single backslash shown in representation of objects. No need to replace. Hint: print the string, not the list containing the string. – Klaus D. Nov 29 '20 at 07:29
  • 1
    If you were to actually write `my_list = ['D:\data\test.xlsx']` and then try to use `my_list`, you would find it doesn't actually mean what you want - the resulting string would contain a tab character rather than a backslash and a t. – user2357112 Nov 29 '20 at 07:30

1 Answers1

4

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.

Keven Li
  • 524
  • 3
  • 8