2017-05-07 50 views
-4
def sstrip(a): 

    b=raw_input("enter the string to be stripped off") 
    i=a.strip(b) 
    print i 

k=raw_input("enter the string") 

sstrip(k) 

输出:地带功能不按预期方式工作

enter the string - is it available? 

enter the string to be stripped off - is 

t available? 

在上述程序中,i是2个字符串的一部分是与它..“它”是一个中word.In那我也被剥夺了。

有人能帮助我

+2

你觉得'a.strip(b)'做什么? “a”是否应该参与剥离动作? ;) – alfasin

+0

如果它不符合预期,请阅读[文档](https://docs.python.org/3/library/stdtypes.html#str.strip) –

+0

我认为OP的难点在于strip()是唯一的我能想到的地方是一组字符被指定为一个字符串。而且他显然并不孤单,因为2.7.13文档中提到“字符参数不是前缀或后缀;相反,其值的所有组合都被剥离”。这一点最近被添加了。 – BoarGules

回答

1

str.strip条由字符(除保持,直至达到未在参数字符),问题是,你包括空格is在你输入之前:

>>> 'is it'.strip('is') 
' it' 
>>> 'is it'.strip('- is') 
't' 

如果你真正想要做的是关闭从一开始涨幅较大的字符串结尾的字符串,那么你可以使用以下命令:

def rcut(a, b): 
    return a[:-len(b)] if a.endswith(b) else a 

def cut(a, b): 
    a = rcut(a, b) 
    return a[len(b):] if a.startswith(b) else a 

print cut('- is it available?', '- is') 
# it available? 
+0

这是非常有用的.. – karthik

0

来看这个提示在程序

b=raw_input("enter the string to be stripped off") 

您预计strip()剥去子前缀和后缀。它没有。 strip()删除不需要的个字符

如果你想从任何地方字符串a删除子b的一个实例:

pieces = a.partition(b) 
i = pieces[0] + pieces[2] 

如果,另一方面,你只想删除前缀和sufffixes,像strip()作用:

i = a 
if i.startswith(b): 
    i = i[len(b):] 
if i.endswith(b): 
    i = i[:len(b)] 

如果你想删除多次出现的前缀或后缀相同的子字符串,又如strip()那样,那么将01对于if,为。

+0

感谢您的回应。有用的一个 – karthik