Skip to main content
 首页 » 编程设计

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

2025年05月04日21txw1958

我的 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 中实现它?

提前致谢!

请您参考如下方法:

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

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