'Removing all instances of the second string from the first
The question states: Write code that takes two strings from the user, and returns what is left over if all instances of the second string is removed from the first. The second string is guaranteed to be no longer than two characters.
I started off with the following:
def remove(l1,l2):
string1 = l1
string2 = l2
result = ""
ctr = 0
while ctr < len(l1):
Since it cannot be longer than 2 characters I think I have to put in an if function as such:
if len(sub) == 2:
if (ctr + 1) < len(string) and string[ctr] == sub[0]
Solution 1:[1]
You could just use the replace
method to remove all occurrences of the the second string from the first:
def remove(s1, s2):
return s1.replace(s2, "")
print remove("hello this is a test", "l")
For a manual method, you can use:
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")
Yields: heo this is a test
Solution 2:[2]
The code looks like this:
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
I got it resolved; just took me a little bit of time.
Solution 3:[3]
You could use list comprehension:
st1 = "Hello how are you"
st2 = "This is a test"
st3 = [i for i in st1 if i not in st2]
print ''.join(st3)
Solution 4:[4]
Using solely the slice method:
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)]
Solution 5:[5]
s1= input()
s2= input()
#get length of each string
l_s1,l_s2= len(s1),len(s2)
#list to store the answer
ans= list()
i=0
#check if more characters are left
#in s1 to b compared
#and length of substring of s1 remaining to
#be compared must be greater than or equal
#to the length of s2
while i<l_s1 and l_s1-i>=l_s2:
j=0
#compare the substring from s1 with s2
while j<l_s2 and s1[i+j]==s2[j]:
j+=1
#if string matches
#discard that substring of s1
#from solution
#and update the pointer i
#accordingly
if j==l_s2:
i+=j
#otherwise append the ith character to
#ans list
else:
ans.append(s1[i])
i+=1
#append if any characters remaining
while i<l_s1:
ans.append(s1[i])
i+=1
print(''.join(ans))
'''
Sample Testcase
1.
kapil
kd
kapil
2.
devansh
dev
ansh
3.
adarsh
ad
arsh
'''
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 | |
Solution 2 | Orange |
Solution 3 | Ajax1234 |
Solution 4 | debiday |
Solution 5 | Devansh Goel |