如何去除包含正斜杠的字符串?

use*_*873 6 python

我是python编程的新手,试图去除包含正斜杠字符的字符串,我期望输出为'/ stack'但是给出如下结果.你能帮助我如何实现预期的输出.还有其他任何简单的方法来实现同样的目标.

>>> name='/stack/overflow'
>>> sub ='/overflow'
>>> name.strip(sub)
'stack'
Run Code Online (Sandbox Code Playgroud)

提前谢谢赫马

Chr*_*nus 7

.strip方法不符合您的想法:

Docstring:
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
Run Code Online (Sandbox Code Playgroud)

所以你正在做的是说"从这个字符串的开头或结尾删除/,o,v,e,r,f,l,o和w."

相反,尝试拆分/,除了最后一个元素,然后重新加入:

In [12]: '/'.join("/stack/overflow".split('/')[:-1])
Out[12]: '/stack'
Run Code Online (Sandbox Code Playgroud)

如果你真的只想删除子字符串'/ overflow',你可以这样做:

In [15]: "/stack/overflow".replace('/overflow', '')
Out[15]: '/stack'
Run Code Online (Sandbox Code Playgroud)