'Why does this function that removes the first occurrence of a string from another string not work correctly?
I tried to write a function that removes the first occurrence of a string from another string:
def removesubstr(substr, x):
a = len(substr)
m = ""
count = 0
b = 0
c = len(x)
while count < c:
for i in x:
if x[b:b+a] == substr:
count = count + 1
m = m + ""
b = b + a
else:
b = b + 1
m = m + i
count = count + 1
return m
print(removesubstr('ara', 'jayaram'))
I'm looking to get an output like 'jaym'
, but I realized that since it's looping 3 steps, Python still takes the full last 3 characters [4:7]
as valid and outputs 'jayram'
. What do I need to change to get 'jaym'
?
Solution 1:[1]
tempstr='jayaram'
tempstr=tempstr.replace("ara", "",1);
You can use python inbuilt replace.you can replace it by blank
Solution 2:[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:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Himanshu dua |
Solution 2 | Tim B |
Solution 3 | gopher |