条带功能未按预期工作

2024-09-30 18:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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是两个字符串的一部分,is和it..“it”是一个mid文字输入我也会脱光衣服。你知道吗

有人能帮我吗


Tags: thetoinputstringrawisdefit
2条回答

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? 

从你程序中的提示来看

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

您希望strip()去掉子字符串前缀和后缀。它不会。strip()删除不需要的字符。你知道吗

如果要从字符串a中的任何位置删除子字符串b的一个实例:

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

另一方面,如果您只想删除前缀和后缀,就像strip()所做的那样:

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

如果你想删除同一前缀或后缀子串的多个出现,同样像strip(),那么用while代替if。你知道吗

相关问题 更多 >