Content · Programming · Python

Python str.removeprefix Method: Usage and Examples

str.removeprefix(prefix) removes an exact prefix if it exists, otherwise returns the original string unchanged. Unlike lstrip(), it does not treat the supplied text as a set of characters. Learn with a clear example.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.removeprefix Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.removeprefix(prefix) removes an exact prefix if it exists, otherwise returns the original string unchanged. Unlike lstrip(), it does not treat the supplied text as a set of characters.

When You Would Use This


Remove a known prefix from a reference code.

Step-by-Step Example


reference_codes = ["INV-0031", "INV-INV-0031", "ORDER-0031"]
for reference_code in reference_codes:
    print(reference_code.removeprefix("INV-"))

How the Example Works


Only one exact INV- prefix is removed from values that begin with it. A different prefix is left untouched; the method does not repeatedly strip all matching characters.

Example Output


0031
INV-0031
ORDER-0031

Try It Yourself


Remove "draft_" only when it occurs at the start of a filename.

Common Beginner Mistakes


  • Using lstrip("INV-") and accidentally deleting unintended letters.
  • Expecting all repeated prefixes to be removed automatically.
  • Assuming case-insensitive matching.

Key Takeaways


  • str.removeprefix(prefix) removes an exact prefix if it exists, otherwise returns the original string unchanged.
  • Only one exact INV- prefix is removed from values that begin with it.
  • Avoid this mistake: Using lstrip("INV-") and accidentally deleting unintended letters.
Share this resourceSend this page to someone who may find it useful.