How to Remove a Prefix from a String in Python

The old way and the new way

How to Remove a Prefix from a String in Python
Photo by Brett Jordan on Unsplash

Nothing warms my heart more than string manipulation — yes, this is sarcasm. Managing strings is not glamorous, it’s not mentally rewarding, but it is a common requirement. Therefore, I do my best to find built-in tools or build reusable tools for the same task.

Removing prefixes is one such task. In this tutorial we’ll go over my old method for removing prefixes from a string and introduce a fresh, newly minted method from version 3.9 that has become my de facto strategy.

Using .startswith() with .replace()

This is a common design pattern that is applicable in a variety of languages. Essentially, we first check if a string starts with our prefix. If it does, then we replace that prefix with an empty string.my_string = 'ABC-1234'
if my_string.startswith('ABC'):
  my_string.replace('ABC','')

We can generalize this into a simple function with two arguments.def strip_prefix(s, p):
  return s.replace(p,'') if s.startswith(p) else s

Note: in actuality, the replace() method can (and should) be replaced by slice notation as it is more performant.def strip_prefix(s, p):
  if s.startswith(p):
     return s[len(p):]
  else:
     return s

This function is pretty easy to read… name makes sense, body is short and straightforward, but it’s still a pain to constantly reinvent the wheel. If only there was a built-in tool for use…🤔

Using .removeprefix()

Fortunately for us, starting in version 3.9, Python released the removeprefix() string method which does exactly what the aforementioned strategy does. In fact, looking at the specification, it’s a near replica of our function with slice notation.

PEP 616 -- String methods to remove prefixes and suffixes
This is a proposal to add two new methods, removeprefix() and removesuffix(), to the APIs of Python's various string…

So, how do we use this method? It’s truly as simple as the following.school_id = 'G00012345'
school_id = school_id.removeprefix('G')

The primary win here is the quality-of-life improvement of never having to copy/paste the old way into a new project again. Additionally — and this is opinion — by having a string method, the syntax is cleaner since only a single argument is passed.


I hope you liked this article! Subscribe to be notified when I publish new articles or even better, consider joining the medium community.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe