2010-01-27 22 views
1

我有我的Python应用程序的字符串看起来是这样的:减少在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实现这一点?

在此先感谢!

回答

5
newString = oldString[:oldString[:-1].rfind('/')] 
# strip out trailing slash ----^  ^---- find last remaining slash 
+0

或者,您可以使用'.rfind('/',0,-2)'。 – kennytm 2010-01-27 08:33:15

+0

太棒了!非常感谢!!! – Neverland 2010-01-27 11:13:10

+2

这确实是最差的答案之一。 – SilentGhost 2010-01-27 14:05:40

5

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

6

听起来像os.path.dirname函数可能是你要找的。您可能需要调用它不止一次:

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

'dirname'通常很有用,但在这种情况下,用户希望'test2'在两种情况下都被删除。 – 2010-01-27 09:02:00

1
>>> import os 
>>> path="how/to/implement/this" 
>>> os.path.split(path) 
('how/to/implement', 'this') 
>>> os.path.split(path)[0] 
'how/to/implement' 
+0

这仅适用于此特定示例(字符串)。但它不是一个通用的解决方案。 – Neverland 2010-01-27 11:10:16

+1

当使用此方法时,什么是断开的字符串示例? – ghostdog74 2010-01-27 11:33:53

0
>>> os.path.split('how/to/implement/this'.rstrip('/')) 
('how/to/implement', 'this') 
>>> os.path.split('how/to/implement/this/'.rstrip('/')) 
('how/to/implement', 'this') 
0
'/'.join(s.split('/')[:-1]+['']) 
+1

大约有6种技术比这更好。 – 2010-01-27 09:43:36

0

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

os.path.dirname(your_argument) 

如果不是,那么你想要:

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

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

+0

“/”是路径分隔符。 – Neverland 2010-01-29 10:42:20