Remove a prefix from a string
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Removing a prefix sounds trivial until the edge cases show up. You usually want to remove a substring only when it appears at the beginning of the string, not everywhere in the text. That distinction matters for file paths, URL prefixes, log labels, and normalized identifiers.
Prefix Removal Is Not Global Replacement
A prefix is a substring anchored at position zero. That means removing a prefix is different from calling a general replace operation.
For example, if you want to strip "api/" from "api/users", you should get "users". But if the input is "backup/api/users", nothing should change because the prefix is not at the start.
That is why this is wrong for prefix handling:
It produces "backup/users", which changes data you did not intend to change.
The Best Option in Modern Python
Python 3.9 added str.removeprefix(). It is the clearest and safest choice when your runtime supports it.
Output:
The behavior is predictable:
- if the string starts with the prefix, it is removed
- if not, the original string is returned unchanged
- if the prefix is the full string, the result is an empty string
That last case is often useful when normalizing identifiers or trimming known protocol markers.
Backward-Compatible Approach
If you need to support Python versions earlier than 3.9, use startswith() with slicing. This is still explicit and efficient.
This is better than trying to use lstrip(). lstrip() does not remove an exact substring. Instead, it removes any leading characters that appear in the argument.
That may remove more characters than you expect, because it treats "abc" as a set of removable characters, not a fixed prefix token.
Working With Multiple Possible Prefixes
Sometimes input can arrive with one of several known prefixes, such as "http://", "https://", or "ftp://". In that case, loop through the allowed prefixes in priority order.
Ordering matters. A more specific prefix should usually come before a shorter one. Otherwise, a broader match can consume part of a string you meant to handle differently.
Prefix Removal in Data Pipelines
This operation becomes more important when you apply it to entire datasets. Suppose a CSV contains product identifiers like "prod-100", "prod-101", and "legacy-9". You may want to strip only the standard prefix before converting values to integers.
The result keeps nonmatching values intact. That makes later validation easier because you can detect unusual formats instead of silently corrupting them.
Performance and Readability
For single strings, the performance difference between removeprefix() and startswith() plus slicing is negligible. The real difference is readability.
- '
removeprefix()states intent directly' - '
startswith()plus slicing works everywhere and is explicit' - '
replace()is usually the wrong semantic choice' - '
lstrip()should not be used for exact prefix removal'
When code reviews happen, semantic clarity matters more than shaving microseconds from a string operation.
Common Pitfalls
The main mistake is using replace() and accidentally removing the target text from the middle of the string as well as the beginning. That changes valid data.
Another common bug is using lstrip() and assuming it removes a fixed word. It does not. It removes any combination of the supplied leading characters.
Be careful with case sensitivity too. "API/users" does not start with "api/". If input is inconsistent, normalize first with lower() or apply a case-insensitive check while preserving the original value if needed.
Finally, think about empty strings and empty prefixes. Python handles them safely, but your business logic may still need validation so accidental empty-prefix inputs do not hide upstream data-quality issues.
Summary
- Removing a prefix means removing text only when it appears at the start of the string.
- In Python 3.9 and newer, prefer
str.removeprefix(). - For older Python versions, use
startswith()plus slicing. - Avoid
replace()for prefix-only logic because it can alter internal text. - Avoid
lstrip()because it removes leading characters, not a fixed substring. - Treat multiple possible prefixes as an ordered matching problem.
Related reading
- Remove accents/diacritics in a string in JavaScript
- Remove all non-numeric characters from a string in swift
- Remove all special characters, punctuation and spaces from string
- Remove ALL white spaces from text
- Remove all occurrences of a value from a list?
- Remove characters except digits from string using Python?
- Remove all whitespace in a string
- Remove all whitespace in a string
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.