【问题标题】:Delete characters in a string Python删除字符串 Python 中的字符
【发布时间】:2017-11-25 06:50:35
【问题描述】:
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"

需要修改原始字符串(复制到新变量中),使其看起来像下面的 new_string。该文件有数千行格式相同(pdf文件的文件路径)。

new_string = "\\\\file_foo\\bar\\foo-bar.pdf"

如何修改 orig_string 使其看起来像新字符串?

编辑: 对不起,我忘了在我的原始帖子中提及。 '\text-to-be-deleted' 不一样。所有文件路径都有不同的 '\text-to-be-deleted' 字符串。

例如

"\\\\file_foo\\bar\\path100\\foo-bar.pdf"
"\\\\file_foo\\bar\\path-sample\\foo-bar.pdf"
"\\\\file_foo\\bar\\another-text-be-deleted\\foo-bar.pdf"

... 等等。

【问题讨论】:

    标签: python string replace filepath


    【解决方案1】:

    我正在考虑您要删除每条路径的倒数第二个元素

    orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
    orig_string = orig_string.split("\\")
    value = orig_string[:-1]
    str1 = orig_string[-1]
    value[-1] = str1
    value[0] = "\\"#Insert "\\" at index 0
    value[1] = "\\"#Insert "\\" at index 1
    print('\\'.join(value))#join the list 
    

    输出

    \\\\file_foo\bar\foo-bar.pdf
    

    【讨论】:

      【解决方案2】:

      使用以下代码:

      orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
      new_string = orig_string
      start = new_string.find("bar\\")
      start = start + 4 # so the start points to char next to bar\\
      end = new_string.find("\\foo")
      temp = new_string[start:end] # this the text to be deleted
      new_string = new_string.replace(temp , "") #this is the required final string
      

      输出:

      \\file_foo\bar\\foo-bar.pdf
      

      【讨论】:

      • 您可以在输出前添加“\\”,方法与第一个答案相同:)
      【解决方案3】:

      如果您知道text-to-be-deleted 是什么,那么您可以使用

      new_string = orig_string.replace('text-to-be-deleted\\','')
      

      如果您只知道要保留的部分,我会使用 str.split() 和您知道的部分作为参数。

      编辑(拆分版): 我会这样做,但那里可能有更清洁的:

      orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
      
      temp_str = orig_string.split('\\')
      idx = temp_str.index('bar')
      
      new_string = temp_str[:idx+1] + temp_str[idx+2:]
      new_string = '\\'.join(new_string)
      print(new_string)#\\file_foo\bar\foo-bar.pdf
      

      【讨论】:

      • 要定位的部分是否总是位于文件路径中的同一点(即文件名之前的目录)?我们可以假设bar 目录总是出现在要删除的部分之前吗?
      • 是的,它始终位于文件名 (.pdf) 之前的同一点。我认为 .split 有效。
      • 编辑了我对 split() 方法的答案(只需将第 3 行中的“bar”更改为您需要的任何内容),希望对您有所帮助!
      【解决方案4】:

      我有一个方法。希望对你有帮助。

      orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
      back_index = orig_string.rfind('\\')
      front_index = orig_string[:back_index].rfind('\\')
      new_string = orig_string[:front_index] + orig_string[back_index:]
      print(new_string)
      

      输出

      '\\\\file_foo\\bar\\foo-bar.pdf'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-29
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多