Python supports plenty of string methods that reduces the need for regular expressions. The removeprefix() and removesuffix() string methods were added in the Python 3.9 version. See PEP 616 for more details.

These methods help to delete an exact substring from the start and end of the input string respectively. Here are some examples:

# remove 'sp' if it matches at the start of the input string
>>> 'spare'.removeprefix('sp')
'are'
# 'par' is present in the input, but not at the start
>>> 'spare'.removeprefix('par')
'spare'

# remove 'me' if it matches at the end of the input string
# only one occurrence of the match will be removed
>>> 'this meme'.removesuffix('me')
'this me'
# characters have to be matched exactly in the same order
>>> 'this meme'.removesuffix('em')
'this meme'

These remove methods will delete the given substring only once from the start or end of the string. On the other hand, the strip methods treat the argument as a set of characters to be matched any number of times in any order until a non-matching character is found. Here are some examples:

>>> 'these memes'.removesuffix('esm')
'these memes'
>>> 'these memes'.rstrip('esm')
'these '

>>> 'effective'.removeprefix('ef')
'fective'
>>> 'effective'.lstrip('ef')
'ctive'

Video demo:


info See also my 100 Page Python Intro ebook.