Replace Backslashes with Forward Slashes in Python

前端 未结 3 1303
粉色の甜心
粉色の甜心 2020-12-10 15:11

I\'m writing a cross platform file explorer in python. I am trying to convert any backslashes in a path into forward slashes in order to deal with all paths in one format.

相关标签:
3条回答
  • 2020-12-10 15:51

    Elaborating this answer, with pathlib you can use the as_posix method:

    >>> import pathlib
    >>> p = pathlib.PureWindowsPath(r'\dir\anotherdir\foodir\more')
    >>> print(p)    
    \dir\anotherdir\foodir\more
    >>> print(p.as_posix())
    /dir/anotherdir/foodir/more
    >>> str(p)
    '\\dir\\anotherdir\\foodir\\more'
    >>> str(p.as_posix())
    '/dir/anotherdir/foodir/more'
    
    0 讨论(0)
  • 2020-12-10 15:52

    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.

    0 讨论(0)
  • 2020-12-10 15:54

    Doesn't this work:

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

    ?

    EDIT:

    Of course this is a string-based solution, and using os.path is wiser if you're dealing with filesystem paths.

    0 讨论(0)
提交回复
热议问题