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中实现这个?
提前致谢!
听起来这个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)
newString = oldString[:oldString[:-1].rfind('/')]
# strip out trailing slash ----^ ^---- find last remaining slash
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1858 次 |
| 最近记录: |