将python中的字符串减少到特定点

Nev*_*and 1 python string path

我的python应用程序中的字符串看起来像这样:

test1/test2/foo/
Run Code Online (Sandbox Code Playgroud)

每当我得到这样一个字符串时,我想减少它,从尾部开始减少直到达到第一个"/".

test1/test2/
Run Code Online (Sandbox Code Playgroud)

更多例子:

foo/foo/foo/foo/foo/  => foo/foo/foo/foo/
test/test/            => test/
how/to/implement/this => how/to/implement/
Run Code Online (Sandbox Code Playgroud)

我怎么能在python中实现这个?

提前致谢!

Gre*_*ill 6

听起来这个os.path.dirname功能可能就是你要找的东西.您可能需要多次调用它:

>>> import os.path
>>> os.path.dirname("test1/test2/")
'test1/test2'
>>> os.path.dirname("test1/test2")
'test1'
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 5

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


Gra*_*aul 5

 newString = oldString[:oldString[:-1].rfind('/')]
 # strip out trailing slash    ----^       ^---- find last remaining slash
Run Code Online (Sandbox Code Playgroud)

  • 这确实是最贫穷的答案之一. (2认同)