Python replace / with \

11,073

Solution 1

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'

Solution 2

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.

Share:
11,073
JiriHnidek
Author by

JiriHnidek

BY DAY: I work at Red Hat as software engineer. I worked at Technical University of Liberec at position Research and Teaching Fellow since 2005. I mostly teached Blender, Computer Graphics, UNIX and Network Protocols and Python. I received Ph.D. title in 2010 for dissertation work: Network Protocols for Graphical Applications. My research is focused on network protocols and computer graphics. I'm also Linux admin of dozens machines. BY NIGHT: I sleep, because I'm mostly exhausted from previous day :-P.

Updated on June 12, 2022

Comments

  • JiriHnidek
    JiriHnidek almost 2 years

    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.