是否有一种优雅的方式来改变URL,例如" file:/// C:/ AAA / BBB"到" C:\ AAA \ BBB"?

时间:2018-03-21 14:18:19

标签: python path

我希望在Python中找到一种优雅的方法,将"file:///C:/AAA/BBB"之类的网址更改为"C:\AAA\BBB"

3 个答案:

答案 0 :(得分:2)

您可以left然后split

join

答案 1 :(得分:1)

    '\\'.join(s.split('/')[3:])

编辑:     从split返回的列表中拼接出'file:'和2''。所以不需要过滤器

答案 2 :(得分:0)

使用s = "file:///C:/AAA/BBB" s_new = s.replace("file:///", "").replace("/", "\\") print(s_new) #C:\AAA\BBB

#@liliscent's solution
%%timeit
'\\'.join(s[len('file:///'):].split('/'))
#1000000 loops, best of 3: 603 ns per loop

#@pault's solution
%%timeit
s_new = s.replace("file:///", "").replace("/", "\\")
#1000000 loops, best of 3: 555 ns per loop

#combination of both above
%%timeit
s[len('file:///'):].replace('/', '\\')
#1000000 loops, best of 3: 396 ns per loop

#Arnab Mukherjee's solution
%%timeit
'\\'.join(s.split('/')[3:])
#1000000 loops, best of 3: 696 ns per loop

时间安排

在我的笔记本电脑上运行python 2.x

public static String getMostRecentVersion(BufferedReader in) throws IOException {
    final Comparator<String[]> version = (s1, s2) -> {
        int res = 0;

        for (int i = 0; i < 5 && res == 0; i++)
            res = Integer.compare(Integer.parseInt(s1[i]), Integer.parseInt(s2[i]));

        return res;
    };

    String str;
    String resStr = null;
    String[] resPparts = null;

    while ((str = in.readLine()) != null) {
        String[] parts = str.split("_");

        if (resStr == null || version.compare(parts, resPparts) > 0) {
            resStr = str;
            resPparts = parts;
        }
    }

    return resStr;
}