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

These methods will help you 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'
# unlike strip methods, substring has to match 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's an example:

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

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

Video demo:


info See also my 100 Page Python Intro ebook.