anas
anas

Reputation: 101

How to convert backslash string to forward slash string in python3?

I am using python3 in my ubuntu machine. I have a string variable which consist a path with backslash and i need to convert it to forward slash string. So i tried

import pathlib
s = '\dir\wnotherdir\joodir\more'
x = repr(s)
p = pathlib.PureWindowsPath(x)
print(p.as_posix())

this will print correctly as

/dir/wnotherdir/joodir/more

but for different other string path, it acts weirdly. Ex, for the string,

'\dir\aotherdir\oodir\more'

it correctly replacing backslashes but the value is wrong because of the character 'a' in original string

/dir/x07otherdir/oodir/more

What is the reason for this behavior?

Upvotes: 1

Views: 425

Answers (1)

lonetwin
lonetwin

Reputation: 991

This has nothing to do with paths per-se. The problem here is that the \a is being interpreted as an ASCII BELL. As a rule of thumb whenever you want to disable the special interpretation of escaped string literals you should use raw strings:

>>> import pathlib
>>> r = r'\dir\aotherdir\oodir\more'
>>> pathlib.PureWindowsPath(r)
PureWindowsPath('/dir/aotherdir/oodir/more')
>>>

Upvotes: 3

Related Questions