【问题标题】:Replacing parts of a string containing directory paths using Python使用 Python 替换包含目录路径的部分字符串
【发布时间】:2019-11-02 12:44:26
【问题描述】:

我有一个大字符串,其中可能包含许多类似于此结构的路径:

dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn

我需要将字符串的a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn 部分之前的所有内容替换为“local/”,这样 结果将如下所示:

本地/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn

字符串可以包含的不仅仅是 dirA/dirB/ 字符串的开头也是。

如何在 Python 中进行这种字符串操作?

【问题讨论】:

    标签: python string directory substring


    【解决方案1】:

    使用正则表达式,您可以用"locals/" 替换直到最后一个"/" 的所有内容

    import re
    s = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
    re.sub(r'.*(\/.*)',r'local\1',s)
    

    你得到:

    'local/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
    

    【讨论】:

    • char / 不需要转义
    • TYVM @Tomerikoo :)
    • 我喜欢这个变化,但它仍然逃脱了哈哈,你可以在第一个正则表达式中将 (\/.*) 更改为 (/.*)
    【解决方案2】:

    使用os 模块

    例如:

    import os
    
    
    path = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
    print(os.path.join("locals", os.path.basename(path)))
    

    【讨论】:

      【解决方案3】:

      另一种方法是将"/" 上的字符串拆分,然后将"locals/" 与结果列表的最后一个元素连接起来。

      s = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
      print("locals/" + s.split("/")[-1])
      #'locals/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
      

      【讨论】:

        【解决方案4】:

        这看起来怎么样?

        inputstring = 'dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
        filename = os.path.basename(inputstring)
        localname =  'local'
        os.path.join(localname, filename)
        

        【讨论】:

        • 或者只是"local/" + os.path.basename(inputstring)
        • @Tomerikoo 。 . .是的,但我相信 os.path.join() 会以与操作系统一致的方式对其进行格式化,因此它可以在任何环境中工作。 Linux 使用正斜杠,Windows 使用反斜杠。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 2020-08-05
        • 2019-09-04
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多