Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Backslashes with Forward Slashes in Python

Tags:

python

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?

like image 898
TartanLlama Avatar asked Nov 07 '10 18:11

TartanLlama


People also ask

How do you replace a string with a forward slash in Python?

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()).

What is the difference between forward slashes and backslashes?

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.

How do you print a front slash in Python?

Use two backslashes to represent a backslashUse the syntax "\\" within the string literal to represent a single backslash.

What does 2 backslashes mean in Python?

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).


2 Answers

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'
like image 152
Stefano M Avatar answered Oct 18 '22 11:10

Stefano M


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.

like image 26
Björn Pollex Avatar answered Oct 18 '22 12:10

Björn Pollex