1

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?

2
  • \a is widely interpreted as the ascii BEL character (07), so it looks like repr(), is performing this translation. A shallow search suggests you should be using x = x.replace("\\", "/") to correct the path separator. Commented Jul 19, 2021 at 13:08
  • still getting the same response as /dir/x07otherdir/oodir/more Commented Jul 19, 2021 at 13:52

1 Answer 1

3

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')
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

this will work. But i need to pass the variable dynamically. That's why a variable is needed here to represent the string path
@AhkamNaseek the raw-string would be created at the point of input. The string-literal would be ideally be escaped when read if it contains a "\" by all low-level apis, so you wouldn't need to call repr() to escape it, eg: ` >>> s = input() \a >>> with open('foo.txt', 'w') as fd: fd.write(s) ... 2 >>> open('./foo.txt').read() '\\a' >>> `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.