简体   繁体   中英

str.replace backslash with forward slash

I would like to replace the backslash \ in a windows path with forward slash / using python. Unfortunately I'm trying from hours but I cannot solve this issue.. I saw other questions here but still I cannot find a solution Can someone help me?

This is what I'm trying:

path = "\\ftac\admin\rec\pir"
path = path.replace("\", "/")

But I got an error (SyntaxError: EOL while scanning string literal) and is not return the path as I want: //ftac/admin/rec/pir , how can I solve it?

I also tried path = path.replace(os.sep, "/") or path = path.replace("\\", "/") but with both methods the first double backslash becomes single and the \a was deleted..

Oh boy, this is a bit more complicated than first appears.

Your problem is that you have stored your windows paths as normal strings, instead of raw strings. The conversion from strings to their raw representation is lossy and ugly.

This is because when you make a string like "\a" , the intperter sees a special character "\x07" .

This means you have to manually know which of these special characters you expect, then [lossily] hack back if you see their representation ( such as in this example ):

def str_to_raw(s):
    raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
    return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)

>>> str_to_raw("\\ftac\admin\rec\pir")
'\\ftac\\admin\\rec\\pir'

Now you can use the pathlib module, this can handle paths in a system agnsotic way. In your case, you know you have Windows like paths as input , so you can use as follows:

import pathlib

def fix_path(path):
    # get proper raw representaiton
    path_fixed = str_to_raw(path)

    # read in as windows path, convert to posix string
    return pathlib.PureWindowsPath(path_fixed).as_posix()

>>> fix_path("\\ftac\admin\rec\pir")
'/ftac/admin/rec/pir'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM