Use removeprefix instead of lstrip to remove a prefix from a string#

Python 3.9 introduced new methods called bytearray.removeprefix() and bytearray.removesuffix() via PEP 616 to remove a prefix or suffix from a string. These methods are similar to str.lstrip() and str.rstrip() but they are more efficient and easier to use as they use a string instead of a set of characters. The latter is useful when you want to remove a prefix or suffix from a string that is not a set of characters.

Lets see an example where we want to remove the prefix www. from a list of URLs as shown below:

Example using lstrip#
def main():
  urls = [
    'www.google.com',
    'www.facebook.com',
    'www.twitter.com',
    'www.wikipedia.org',
  ]

  for url in urls:
    print(url.lstrip('www.'))


if __name__ == '__main__':
  main()

Everything looks fine until we have a URL that does not conform to the pattern. For example, if we have a URL like www.wikipedia.org, the output will be ikipedia.org which is not what we want. The method str.lstrip() removes all the characters in the set from the left side of the string until it encounters a character that is not in the set. This is where a lot of people get confused.

Output of the example using lstrip#
$ python3 main.py
google.com
facebook.com
twitter.com
ikipedia.org

If we rewrite the above example using bytearray.removeprefix(), we will get the desired output as the output will be wikipedia.org instead of ikipedia.org.

Example using removeprefix#
def main():
  urls = [
    'www.google.com',
    'www.facebook.com',
    'www.twitter.com',
    'www.wikipedia.org',
  ]

  for url in urls:
    print(url.removeprefix('www.'))


if __name__ == '__main__':
  main()

Checking the output confirms that the method bytearray.removeprefix() is working as expected and all the URLs are printed correctly.

Output of the example using removeprefix#
$ python3 main.py
google.com
facebook.com
twitter.com
wikipedia.org

PEP 616 is a clear example of how Python is evolving and making things easier for developers. The new methods bytearray.removeprefix() and bytearray.removesuffix() are more efficient and easier to use than the existing methods str.lstrip() and str.rstrip(). It also shows that keeping an eye new features and changes in the language is important for developers to keep the code up to date and efficient.