Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.removeprefix() method

Reference for Python str.removeprefix() (3.9+): remove an exact prefix from a string if present, and why it differs from lstrip(), which removes characters.

The str.removeprefix() method returns a copy of the string without the given prefix, if the string starts with it. If it does not, you get the string back unchanged. It was added in Python 3.9.

It does exactly one job: remove one literal prefix, once. That is different from lstrip(), which removes any leading characters from a set, and a classic source of bugs.

Python
print("test_login".removeprefix("test_"))   # login

Try it

Python Removing a prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python removeprefix vs lstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.removeprefix(prefix)
Name Description
prefix The exact string to remove from the start.

Return value: a new string. If the string does not start with prefix, the result is equal to the original (CPython returns the same object for exact str values).

Raises: TypeError if prefix is not a string.

Usage notes

  • Removes at most one copy. "test_test_x".removeprefix("test_") leaves "test_x".
  • Not lstrip(). lstrip("ban") strips any run of the characters b, a and n, so "banana".lstrip("ban") is an empty string. Use removeprefix() whenever you mean a whole prefix.
  • No error when absent, so no if s.startswith(p): guard is needed. Test with startswith() only if you need to know whether something was removed.
  • Strings are immutable; the original is never changed.
  • Before Python 3.9 the idiom was s[len(p):] if s.startswith(p) else s.
  • Case-sensitive. Normalize with lower() first if you need caseless matching, but note that you then lose the original case in the result.
  • Also available on bytes and bytearray.