How do I remove a substring from the end of a string in Python?

PythonServer Side ProgrammingProgramming

If you want to remove a substring from the end of a string, you should fisrt check if the string ends with that substring. If it does, then slice the string keeping only the part without substring. For example,

def rchop(string, ending):
  if string.endswith(ending):
    return string[:-len(ending)]
  return string
chopped_str = rchop('Hello world', 'orld')
print chopped_str

This will give the output:

Hello w

If speed is not important, you can also use a regex here. For example,

>>> import re
>>> re.sub('orld$', '', 'Hello world')
Hello w
Updated on 30-Sep-2019 07:56:50