JiriHnidek
JiriHnidek

Reputation: 563

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.

Upvotes: 5

Views: 18510

Answers (3)

BattleDrum
BattleDrum

Reputation: 818

This worked for me:

unix_path= '/path/to/some/directory'

print(unix_path.replace('/','\\'))

result:

\path\to\some\directory

Upvotes: 0

Joël
Joël

Reputation: 2832

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'

Upvotes: 7

TigerhawkT3
TigerhawkT3

Reputation: 49330

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.

Upvotes: 4

Related Questions