str.removeprefix()
Strip an exact prefix — the intent-preserving alternative to lstrip that does not surprise you with character-set semantics.
Demo
removeprefix strips an EXACT substring from the start — at most once. If the string does not start with the prefix, the original is returned unchanged. Unlike lstrip, the argument is a substring, not a character set — "un" removes exactly "un" once, not any leading "u" and "n" characters in any order.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| prefix | str | yes | The exact substring to remove from the start. If the string does not start with this exact substring, the original is returned unchanged. |
Return value
str — A copy of the string with the exact SUBSTRING `prefix` removed from the start, IF the string starts with it. Otherwise the string is returned unchanged. Removes at most one occurrence.
Common patterns
host_path = url.removeprefix("https://")
name = symbol.removeprefix("my_module.")
if key.startswith("_"): real_key = key.removeprefix("_")
Examples
Pitfalls
"ununhappy".removeprefix("un")
s = "ununhappy" while s.startswith("un"): s = s.removeprefix("un")
"hello".removeprefix("")
if prefix: s = s.removeprefix(prefix)
"unnnnhappy".lstrip("un")
"unnnnhappy".removeprefix("un")
"unhappy".removeprefix("un") # 3.8
def removeprefix(s, p): return s[len(p):] if s.startswith(p) else s
When to use
- Stripping a KNOWN, exact leading substring
- URL/URI scheme removal
- Namespace or module-prefix trimming
- Any place lstrip would have been the wrong tool because of character-set semantics
- Multi-occurrence removal → loop with while + startswith
- Character-set removal → str.lstrip is the correct tool
- Case-insensitive prefix removal → casefold both sides, or use regex
- Python 3.8 or earlier → use the s[len(p):] idiom instead
Notes
FAQ
Because lstrip strips a CHARACTER SET, not a substring. "https://".lstrip("https://") strips leading h, t, p, s, colon, and slash in any combination, which is almost never what people want. removeprefix does exact-prefix removal, which is almost always what people meant when they reached for lstrip.