Convert Backward Slash to Forward Slash in Python

How to convert back-slashes to forward-slashes?

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.

Convert backward slash to forward slash in python

Don't do this. Just use os.path and let it handle everything. You should not explicitly set the forward or backward slashes.

>>> var=r'C:\dummy_folder\a.txt'
>>> var.replace('\\', '/')
'C:/dummy_folder/a.txt'

But again, don't. Just use os.path and be happy!

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

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

Replace Backslashes with Forward Slashes in Python

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.

Python replace forward slash with back slash

The second argument should be a string, not a regex pattern:

foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')

Use Python to replace forward slashes in string to backslashes

Two backslashes mean a literal backslash:

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

How to replace single forward slashes with single backward slashes

The output you're seeing is the repr representation of the string.

>>> s = 'a26/n//3@5'
>>> s
'a26/n//3@5'
>>> s.replace('/', '\\')
>>> s
>>> 'a26\\n\\\\3@5' # repr representation ('\' as '\\')

To get your expected output you should print the string:

>>> new_s = s.replace('/', '\\')
>>> print(new_s)
>>> a26\n\\3@5

Edit: Fixed typo



Related Topics



Leave a reply



Submit