Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert Back Slashes to forward slashes

Tags:

python

replace

I am working in python and I need to convert this:

C:\folderA\folderB to C:/folderA/folderB

I have three approaches:

dir = s.replace('\\','/')  dir = os.path.normpath(s)   dir = os.path.normcase(s) 

In each scenario the output has been

C:folderAfolderB

I'm not sure what I am doing wrong, any suggestions?

like image 901
John87 Avatar asked Aug 05 '14 19:08

John87


People also ask

How do you change backward slash to forward slash?

By default the <Leader> key is backslash, and <Bslash> is a way to refer to a backslash in a mapping, so by default these commands map \/ and \\ respectively. Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

How do you change the backward slash in Python?

We can use the replace() function to replace the backslashes in a string with another character. To replace all backslashes in a string, we can use the replace() function as shown in the following Python code.

How do you forward a slash in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash.

How do you change a double backslash to a single backslash in Python?

Just use . replace() twice! first operation creates ** for every \ and second operation escapes the first slash, replacing ** with a single \ .


2 Answers

Your specific problem is the order and escaping of your replace arguments, should be

s.replace('\\', '/') 

Then there's:

posixpath.join(*s.split('\\')) 

Which on a *nix platform is equivalent to:

os.path.join(*s.split('\\')) 

But don't rely on that on Windows because it will prefer the platform-specific separator. Also:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

like image 23
Jason S Avatar answered Sep 29 '22 10:09

Jason S


I recently found this and thought worth sharing:

import os  path = "C:\\temp\myFolder\example\\"  newPath = path.replace(os.sep, '/')  print newPath   Output:<< C:/temp/myFolder/example/  >> 
like image 157
Numabyte Avatar answered Sep 29 '22 11:09

Numabyte