Remove substring only at the end of string

Viewed 80066

I have a bunch of strings, some of them have ' rec'. I want to remove that only if those are the last 4 characters.

So in other words I have

somestring = 'this is some string rec'

and I want it to become

somestring = 'this is some string'

What is the Python way to approach this?

11 Answers

Starting in Python 3.9, you can use removesuffix:

'this is some string rec'.removesuffix(' rec')
# 'this is some string'

Here is a one-liner version of Jack Kelly's answer along with its sibling:

def rchop(s, sub):
    return s[:-len(sub)] if s.endswith(sub) else s

def lchop(s, sub):
    return s[len(sub):] if s.startswith(sub) else s

Taking inspiration from @David Foster's answer, I would do

def _remove_suffix(text, suffix):
    if text is not None and suffix is not None:
        return text[:-len(suffix)] if text.endswith(suffix) else text
    else:
        return text

Reference: Python string slicing


def remove_trailing_string(content, trailing):
    """
    Strip trailing component `trailing` from `content` if it exists.
    """
    if content.endswith(trailing) and content != trailing:
        return content[:-len(trailing)]
    return content
Related