Replace backslash with slash in Python

I am writing a cross-platform file explorer in python. I am trying to convert any backslashes in a path to slashes in order to deal with all paths in the same format.

I tried not only to use string.replace (str, '\\', '/'), but to manually create a method to search by string and replace instances, and both of them work incorrectly because the path name, for example:

\dir\anotherdir\foodir\more

changes to:

/dir/anotherdir\x0oodir/more

I guess this has something to do with how Python represents escape characters or something like that. How to prevent this?

+3
source share
2 answers

os.path . Python 3 pathlib, , , .

+7

:

    >>> s = 'a\\b'
    >>> s
    'a\\b'
    >>> print s
    a\b
    >>> s.replace('\\','/')
    'a/b'

?

EDIT:

, , os.path , .

+1

Source: https://habr.com/ru/post/1773524/


All Articles