How do I replace the matching end of a string in Python?

Question:

I am learning how to apply string operations in Python, How would I go about replacing the last occurrence of a substring?

Question/Code given to debug:

The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made).

def replace_ending(sentence, old, new):
    # Check if the old string is at the end of the sentence 
    if ___:
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = ___
        new_sentence = ___
        return new_sentence

    # Return the original sentence if there is no match 
    return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"

My code:

def replace_ending(sentence, old, new):
    # Check if the old string is at the end of the sentence 
    if sentence.endswith(old):
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = sentence.index(old)
        new_sentence = sentence[0:i] + new
        return new_sentence

    # Return the original sentence if there is no match 
    return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"

I’m having issues with substrings that occur more than once.
I know that this question has been asked, but the answers given were too advanced, and I wasn’t sure if adding an answer (posed as a question) would get a response on that specific thread (and I don’t have enough reps to make a comment). So I decided to create my own question. Any help is greatly appreciated.

Asked By: 305Curtis

||

Answers:

Using .index(old) is wrong since it will match the first occurrence of the word. Checking with .endswith(old) is more than enough. After that, since you already know that the strings ends with old, you can just discard len(old) characters from the end of the string.

def replace_ending(sentence, old, new):
    if sentence.endswith(old):
        return sentence[:-len(old)] + new
    return sentence
Answered By: Marco Bonelli

Use string reverse and replace tricks:

def replace_last(s, repstr, substr):
    '''reverse string, replace only one occurrence 
       reverse back'''

     s = s[::-1].replace(repstr[::-1],substr[::-1],1)
     return s[::-1]

test = 'abcabc'
repstr = 'abc'
substr = 'xyz'

print(replace_last(test, repstr, substr))
# 'abcxyz'

Basics are we take the strings and reverse the order so 'abcabc'[::-1] == 'cbacba' we then use `replace(string, substring, occurrence=1) and reverse back 🙂 This will work even if the word is not at the end of the sentence

enter image description here

Answered By: Prayson W. Daniel
def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
if sentence.endswith(old):
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the 
    # end with the new string
    i = len( sentence.split())
    new_sentence = sentence[:-len(old)] + new 
    return new_sentence

# Return the original sentence if there is no match 
return sentence

There is a very easy way to do this, follow my steps

str = "stay am stay am  delete am"
#  want to remove the last am
str = str[:str.rfind('am')]
print(str)
Answered By: Oishik Sinha
def replace_ending(sentence, old, new):
    if old in sentence:
        sentence = sentence[::-1]
        index = sentence.index(old[::-1])
        new_sentence = sentence[:index] + new[::-1] + sentence[(len(old)+index):]
        return new_sentence[::-1]
    return sentence
  • First, reverse the sentence given and also the string that has to be replaced.
  • Then find the index of the reversed string (it only gives the first occurance).
  • Then replace that reversed old string with reversed new string.
  • At last reverse the entire new_sentence to get the proper result.
Answered By: Koushik Shirali

The question has some condition like you need to fill in the blank. So accordingly here is my answer satisfying the question.

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
if sentence.endswith(old):
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the 
    # end with the new string
    i = sentence[:-len(old)]
    new_sentence = i+new
    return new_sentence

# Return the original sentence if there is no match 
return sentence
Answered By: A.A

Use a regular expression with the re.sub() function:

import re
print(re.sub("abc$", "xyz", "abcabc"))
Answered By: user20283776
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.