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.
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
| Parameter | What it is |
|---|---|
prefixrequired | 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
url = "https://example.com"
print(url.removeprefix("https://"))
print(url.removeprefix("ftp://"))example.com https://example.com
No match, no change, no error.
2removeprefix() vs lstrip()
url = "https://shop.example.com"
print(url.lstrip("https://"))
print(url.removeprefix("https://"))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
files = ["img_beach.jpg", "img_city.jpg", "notes.txt"]
print([f.removeprefix("img_") for f in files])['beach.jpg', 'city.jpg', 'notes.txt']
4It only removes one copy
print("abab-x".removeprefix("ab"))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.
text = "Mr. Smith"
prefix = "Mr. "
if text.startswith(prefix):
text = text[len(prefix):]
print(text)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().