Skip to content Skip to sidebar Skip to footer

Write A Function That Removes The First Occurrence Of A String From Another String.

For the above problem, i tried the below code. def removesubstr(substr,x): a = len(substr) m = '' count = 0 b = 0 c= len(x) while count

Solution 1:

tempstr='jayaram'
tempstr=tempstr.replace("ara", "",1);

You can use python inbuilt replace.you can replace it by blank


Solution 2:

Assuming you are supposed to do this yourself rather than using the built in library functions...

You seem to be making this rather more complicated than you need to, you should also use much more meaningful variable names. a, b, and m are all meaningless.

You want something like:

sublen = len(substr)
strlen = len(x)
loop = 0
while loop+sublen < strlen:
    loop = loop +1;
    if x[loop:loop+sublen] == substr:
         return x[0:loop]+x[loop+sublen:strlen]

return x

Solution 3:

def remove(s, text):
  if text.find(s) == -1:
        return text
  else:
    new = text[0:text.find(s)]+text[text.find(s)+len(s):len(text)]
    return new

Post a Comment for "Write A Function That Removes The First Occurrence Of A String From Another String."