简体   繁体   English

str. 用正斜杠替换反斜杠

[英]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?我想用正斜杠/使用 python 替换 windows 路径中的反斜杠 \。不幸的是,我尝试了几个小时,但我无法解决这个问题。我在这里看到了其他问题,但仍然找不到解决方案 有人可以帮我吗?

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?但是我收到一个错误(SyntaxError: EOL while scanning string literal)并且没有返回我想要的路径: //ftac/admin/rec/pir ,我该如何解决?

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..我也试过path = path.replace(os.sep, "/")path = path.replace("\\", "/")但使用这两种方法时,第一个双反斜杠变成单斜杠,\a 被删除。 .

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.您的问题是您已将 windows 路径存储为普通字符串,而不是原始字符串。 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" .这是因为当你创建一个像"\a"这样的字符串时,intperter 会看到一个特殊字符"\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 ):这意味着你必须手动知道你期望这些特殊字符中的哪些,然后如果你看到它们的表示(例如在这个例子中)[lossily] hack back:

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.现在您可以使用pathlib模块,它可以以系统无关的方式处理路径。 In your case, you know you have Windows like paths as input , so you can use as follows:在您的情况下,您知道您有Windows 等路径作为输入,因此您可以按如下方式使用:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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