从第一个字符串中删除第二个字符串的所有实例

时间:2017-04-05 13:30:21

标签: python string list

问题陈述:编写从用户获取两个字符串的代码,如果第一个字符串的所有实例都从第一个字符串中删除,则返回剩余的字符串。第二个字符串保证不超过两个字符。

我从以下开始:

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

因为它不能超过2个字符,我想我必须放入一个if函数:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分: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

我解决了;我带了一点时间。

答案 3 :(得分:0)

单独使用 slice 方法:

def remove_all(substr,theStr):
    num=theStr.count(substr)
    for i in range(len(theStr)):
        finalStr=""
        if theStr.find(substr)<0:
            return theStr
        elif theStr[i:i+len(substr)]==substr:
            return theStr[0:i]+ theStr[i+len(substr*num):len(theStr)]