2017-05-07 51 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