Avoiding the use of Python functions.
Method 1
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
i = 0
while i < len(s) - len(substr) + 1:
# Check if substring starts at i
if s[i:i+len(substr)] == substr:
break
i += 1
else:
# break not hit, so substr not found
return s
# break hit
return s[:i] + s[i+len(substr):]
Method 2
If the range function can be used, the above can be written more compactly as follows.
def remove_substring_from_string(s, substr):
'''
find start index in s of substring
remove it by skipping over it
'''
for i in range(len(s) - len(substr) + 1):
if s[i:i+len(substr)] == substr:
break
else:
# break not hit, so substr not found
return s
return s[:i] + s[i+len(substr):]
Test
print(remove_substring_from_string("I have nothing to declare except my genuis", " except my genuis"))
# Output: I have nothing to declare'
s. Yourforloop iterates over the characters froms. Sincesis always a character froms,substr in sis alwaysTrue. So it's not what you want. What you need to do first is to find the position ofsubstrins, which you can do by iterating over the possible positions where the substring might be found, take a slice of the string at that position (using the length of the substring to calculate the end of the slice), and check to see whether the slice equals the substring.remove_substring_from_string("aaa", "aa")only an"a"or an empty string? I.e., how are overlapping parts meant to be handled?