2017-04-05 35 views
0

问题状态:编写从用户接收两个字符串的代码,并返回从第一个字符串中删除第二个字符串的所有实例时剩下的内容。第二个字符串保证不超过两个字符。从第一个字符串中删除第二个字符串的所有实例

我开始了与以下:

def remove(l1,l2): 
    string1 = l1 
    string2 = l2 
    result = "" 
    ctr = 0 
    while ctr < len(l1): 

,因为它不能超过2个字符,我想我有,如果功能这样就摆在一个较长:

if len(sub) == 2: 
    if (ctr + 1) < len(string) and string[ctr] == sub[0] 
+2

你能提供一个例子吗?如果第二个字符串是“aa”而您的输入字符串是“aaa”呢? – timgeb

+0

你是指字符串列表吗?嗯,请分享一下l1和l2的例子。 –

+0

是故意的'while'循环吗? – patrick

回答

1

你可以只使用replace方法从第一个字符串中删除所有出现的第二个字符串:

def remove(s1, s2): 
    return s1.replace(s2, "") 

print remove("hello this is a test", "l") 

对于手动方法,你可以使用:

def remove(s1, s2): 
    newString = [] 
    if len(s2) > 2: 
    return "The second argument cannot exceed two characters" 
    for c in s1: 
    if c not in s2: 
     newString.append(c) 
    return "".join(newString) 

print remove("hello this is a test", "l") 

产量:heo this is a test

+0

因为这是一项任务,所以使用'replace'可能违背练习的精神:) – timgeb

+0

这也是我用过的,但不幸的是我受限于len()和append()的约束,我不允许使用替换功能。 – Orange

+0

@timgeb不幸的是,哟是正确的......哈哈 – Orange

0

你可以使用列表理解:

st1 = "Hello how are you" 
st2 = "This is a test" 
st3 = [i for i in st1 if i not in st2] 
print ''.join(st3) 
0

的代码看起来是这样的:

def remove(l1,l2): 
    string1 = l1 
    string2 = l2 
    ctr = 0 
    result = "" 
    while ctr < len(string1): 
     if string1[ctr : ctr + len(string2)] == string2: 
      ctr += len(string2) 
     else: 
      result += string1[ctr] 
      ctr += 1 

    return result 

我解决了它;只是花了我一点时间。

相关问题