I'm writing a cross platform file explorer in python. I am trying to convert any backslashes in a path into forward slashes in order to deal with all paths in one format.
I've tried not only using string.replace(str, '\\', '/'), but also creating a method manually to search through the string and replace the instances, and both do not work properly, as a path name such as:
\dir\anotherdir\foodir\more
changes to:
/dir/anotherdir\x0oodir/more
I am assuming that this has something to do with how Python represents escape characters or something of the sort. How do I prevent this happening?
A forward-slash (/) in a Python string can be replaced by a backslash (\) using the String replace() function, translate() method, or regular expression(re. sub()).
There are two types of slashes: a backslash (\) and a forward slash (/). The backslash is used only for computer coding. The forward slash, often simply referred to as a slash, is a punctuation mark used in English.
Use two backslashes to represent a backslashUse the syntax "\\" within the string literal to represent a single backslash.
In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or whole number).
Elaborating this answer, with pathlib you can use the as_posix method:
>>> import pathlib
>>> p = pathlib.PureWindowsPath(r'\dir\anotherdir\foodir\more')
>>> print(p)
\dir\anotherdir\foodir\more
>>> print(p.as_posix())
/dir/anotherdir/foodir/more
>>> str(p)
'\\dir\\anotherdir\\foodir\\more'
>>> str(p.as_posix())
'/dir/anotherdir/foodir/more'
You should use os.path
for this kind of stuff. In Python 3, you can also use pathlib
to represent paths in a portable manner, so you don't have to worry about things like slashes anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With