'Removing the first occurrence of a string from another string in Python
I am trying to write a function that will remove the first occurrence of a string from another string, like:
remove("an", "banana") == "bana"
The goal is not to use a built-in method, but rather to make up my own function using slicing and indexing techniques.
This is what I've tried so far:
def remove(substring, string):
sublen = len(substring)
new_string = ""
for i in range(len(string)):
# test if string slices are different from substring and if
# they are, add them to new_string variable
if string[i:i+sublen+1] != substring:
new_string += string[i:i+sublen+1]
return new_string
I have come across another post where someone asked the same question as I did (Write a function that removes the first occurrence of a string from another string.), but I could not understand how the solutions offered were supposed to work. I would appreciate it if someone could point me in the right direction, or at least help understand what I'm missing here.
Solution 1:[1]
Refactoring your code
def remove(substring, string):
sublen = len(substring)
new_string = ""
for i in range(len(string)):
if string[i:i+sublen] == substring:
# found so append remaining string
new_string += string[i+sublen:]
break
else:
new_string += string[i] # not found so append character
return new_string
print(remove("today", 'today is friday, the last friday of the month'))
Output
is friday, the last friday of the month
Alternate Solution (from your link)
def remove(substring, string)
return string.replace(substring, '', 1)
This uses the replace
function to replace the first occurrence of a string.
Python String | replace provides a good description of how this works.
Solution 2:[2]
You can also use a different approach: after you've found the indexes of the substring, create another string by concatenating two other pieces of the string without the substring:
def remove(substring, string):
sublen = len(substring)
for i in range(len(string)):
if string[i : i + sublen] == substring:
return string[:i] + string[i + sublen:]
return string
print(remove("wor", "Hello, world")) # Hello, ld
print(remove("an", "banana")) # bana
print(remove("x", "banana")) # banana
Solution 3:[3]
DarrylG's string.replace(substring, '', 1)
is better but you could also use split
and join
:
def remove1st(string,substring):
return "".join(string.split(substring,1)) #
remove1st("banana","na") # 'bana'
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 | mkrieger1 |
Solution 2 | hurlenko |
Solution 3 | mkrieger1 |