Skip to content

Instantly share code, notes, and snippets.

@Codehunter-py
Created December 1, 2021 19:13
Show Gist options
  • Save Codehunter-py/05b9849ec61c67f2c8f86cc1712dbf5a to your computer and use it in GitHub Desktop.
Save Codehunter-py/05b9849ec61c67f2c8f86cc1712dbf5a to your computer and use it in GitHub Desktop.
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.
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(old)
new_sentence = sentence[:-i]+new
return new_sentence
# Return the original sentence if there is no match
return sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment