String method

str.removeprefix()

Removes an exact piece of text from the start of a string, if the string begins with it. Otherwise the string comes back as it is.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.removeprefix(prefix)

removeprefix() checks whether the string starts with prefix and, if it does, returns the rest. If it does not, you get the original text back. It was added in Python 3.9.

It is the right tool for removing a fixed beginning: "https://" from a web address, "img_" from a file name, "Mr. " from a name.

It replaces a common mistake with str.lstrip(): lstrip("https://") removes any of those characters, again and again, and can eat into the text. removeprefix() removes the exact text, once.

Parameters

ParameterWhat it is
prefix
required
The exact text to remove from the start.

Return value

A new string without the prefix, or a copy of the original if it did not start with it.

Examples

1Remove a fixed beginning

Pythoneditable
url = "https://example.com"
print(url.removeprefix("https://"))
print(url.removeprefix("ftp://"))
Output
example.com
https://example.com

No match, no change, no error.

2removeprefix() vs lstrip()

Pythoneditable
url = "https://shop.example.com"
print(url.lstrip("https://"))
print(url.removeprefix("https://"))
Output
op.example.com
shop.example.com

lstrip() also removed the s and h of shop, because they are in its set of characters.

3Clean a list of file names

Pythoneditable
files = ["img_beach.jpg", "img_city.jpg", "notes.txt"]
print([f.removeprefix("img_") for f in files])
Output
['beach.jpg', 'city.jpg', 'notes.txt']

4It only removes one copy

Pythoneditable
print("abab-x".removeprefix("ab"))
Output
ab-x

Common mistakes

Needing it on Python 3.8 or older

removeprefix() does not exist before 3.9. The classic replacement checks and slices.

Pythoneditable
text = "Mr. Smith"
prefix = "Mr. "
if text.startswith(prefix):
    text = text[len(prefix):]
print(text)
Output
Smith

Questions people ask

What is the difference between removeprefix() and lstrip()?

removeprefix("ab") removes the exact text "ab" once. lstrip("ab") removes any mix of a and b characters, as many as there are.

Is removeprefix() case-sensitive?

Yes. "Hello".removeprefix("he") changes nothing.

How do I remove text from the end?

Use str.removesuffix().

Spotted a mistake on this page? Tell us