【问题标题】:Reduce strings in python to a specific point将python中的字符串减少到特定点
【发布时间】:2011-01-09 20:43:20
【问题描述】:

我的 python 应用程序中有这样的字符串:

test1/test2/foo/

每次得到这样的字符串,我都想减少它,从尾部开始减少,直到到达第一个“/”。

test1/test2/

更多示例:

foo/foo/foo/foo/foo/  => foo/foo/foo/foo/
test/test/            => test/
how/to/implement/this => how/to/implement/

如何在 python 中实现?

提前致谢!

【问题讨论】:

    标签: python string path


    【解决方案1】:

    如果你的意思是路径分隔符中的“/”,你想要的功能是:

    os.path.dirname(your_argument)
    

    如果没有,那么你想要:

    def your_function(your_argument):
        result= your_argument.rstrip("/").rpartition("/")[0]
        if result:
            return result + "/"
        return result
    

    请指定当“test/”用作参数时应该是什么结果:应该是“/”还是“”?我在上面的代码中假设了第二个。

    【讨论】:

      【解决方案2】:
      '/'.join(s.split('/')[:-1]+[''])
      

      【讨论】:

      • 大约有六种技术比这更好。
      【解决方案3】:
      >>> os.path.split('how/to/implement/this'.rstrip('/'))
      ('how/to/implement', 'this')
      >>> os.path.split('how/to/implement/this/'.rstrip('/'))
      ('how/to/implement', 'this')
      

      【讨论】:

        【解决方案4】:
        >>> import os
        >>> path="how/to/implement/this"
        >>> os.path.split(path)
        ('how/to/implement', 'this')
        >>> os.path.split(path)[0]
        'how/to/implement'
        

        【讨论】:

        • 这只适用于这个特定的例子(字符串)。但这不是一个通用的解决方案。
        • 使用此方法时中断的字符串示例有哪些?
        【解决方案5】:
         newString = oldString[:oldString[:-1].rfind('/')]
         # strip out trailing slash    ----^       ^---- find last remaining slash
        

        【讨论】:

        • 您也可以使用.rfind('/', 0, -2)
        • 这确实是最差的答案之一。
        • 我同意 SilentGhost,这确实是最糟糕的选择之一。基于 os.path 的答案要好得多。
        • 好吧,我不知道它是用于路径的!
        • 这个解决方案最适合我。谢谢!
        【解决方案6】:

        听起来os.path.dirname 函数可能是您正在寻找的。您可能需要多次调用它:

        >>> import os.path
        >>> os.path.dirname("test1/test2/")
        'test1/test2'
        >>> os.path.dirname("test1/test2")
        'test1'
        

        【讨论】:

        • dirname 通常很有用,但在这种情况下,用户希望在两种情况下都删除 test2
        【解决方案7】:

        str.rsplit()maxsplit 参数。或者,如果这是一条路径,请查看 os.pathurlparse

        【讨论】:

          猜你喜欢
          • 2015-02-10
          • 2016-10-06
          • 2017-02-14
          • 1970-01-01
          • 2019-09-06
          • 1970-01-01
          • 1970-01-01
          • 2020-02-26
          • 2018-12-21
          相关资源
          最近更新 更多