Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace / with \

I write some simple Python script and I want to replace all characters / with \ in text variable. I have problem with character \, because it is escape character. When I use replace() method:

unix_path='/path/to/some/directory'
unix_path.replace('/','\\')

then it returns following string: \\path\\to\\some\\directory. Of course, I can't use: unix_path.replace('/','\'), because \ is escape character.

When I use regular expression:

import re
unix_path='/path/to/some/directory'
re.sub('/', r'\\', unix_path)

then it has same results: \\path\\to\\some\\directory. I would like to get this result: \path\to\some\directory.

Note: I aware of os.path, but I did not find any feasible method in this module.

like image 343
JiriHnidek Avatar asked Jan 25 '16 12:01

JiriHnidek


2 Answers

You missed something: it is shown as \\ by the Python interpreter, but your result is correct: '\\'is just how Python represents the character \ in a normal string. That's strictly equivalent to \ in a raw string, e.g. 'some\\path is same as r'some\path'.

And also: Python on windows knows very well how to use / in paths.

You can use the following trick though, if you want your dislpay to be OS-dependant:

In [0]: os.path.abspath('c:/some/path')
Out[0]: 'c:\\some\\path'
like image 200
Joël Avatar answered Oct 23 '22 10:10

Joël


You don't need a regex for this:

>>> unix_path='/path/to/some/directory'
>>> unix_path.replace('/', '\\')
'\\path\\to\\some\\directory'
>>> print(_)
\path\to\some\directory

And, more than likely, you should be using something in os.path instead of messing with this sort of thing manually.

like image 21
TigerhawkT3 Avatar answered Oct 23 '22 11:10

TigerhawkT3