string-manipulation
programming
text-processing
python
code-snippets

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.

Practice ML system design

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:

python
text = "backup/api/users"
print(text.replace("api/", ""))

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.

python
1examples = [
2    "api/users",
3    "backup/api/users",
4    "api/",
5    "users",
6]
7
8for value in examples:
9    print(value.removeprefix("api/"))

Output:

text
1users
2backup/api/users
3
4users

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.

python
1def remove_prefix(text: str, prefix: str) -> str:
2    if text.startswith(prefix):
3        return text[len(prefix):]
4    return text
5
6
7print(remove_prefix("api/users", "api/"))
8print(remove_prefix("users", "api/"))
9print(remove_prefix("api/", "api/"))

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.

python
value = "abcab-report"
print(value.lstrip("abc"))

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.

python
1def strip_first_matching_prefix(text: str, prefixes: list[str]) -> str:
2    for prefix in prefixes:
3        if text.startswith(prefix):
4            return text[len(prefix):]
5    return text
6
7
8url = "https://example.com/docs"
9cleaned = strip_first_matching_prefix(url, ["https://", "http://", "ftp://"])
10print(cleaned)

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.

python
1def normalize_product_id(raw: str) -> str:
2    return raw.removeprefix("prod-")
3
4
5ids = ["prod-100", "prod-101", "legacy-9"]
6print([normalize_product_id(item) for item in ids])

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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Practice ML system design

All Rights Reserved.