How to Remove Prefix from String in Python Easily
str.removeprefix(prefix) to remove a prefix from a string safely. For earlier versions, check if the string starts with the prefix and then use slicing like string[len(prefix):] to remove it.Syntax
The main method to remove a prefix from a string in Python 3.9+ is str.removeprefix(prefix). Here, prefix is the substring you want to remove if it appears at the start of the string.
For older Python versions, you can use slicing combined with str.startswith(prefix) to check if the prefix exists before removing it.
result = string.removeprefix(prefix) # Older Python versions if string.startswith(prefix): result = string[len(prefix):] else: result = string
Example
This example shows how to remove the prefix 'Hello, ' from a string using removeprefix(). It also shows the older method using slicing for compatibility.
string = "Hello, world!" prefix = "Hello, " # Using removeprefix (Python 3.9+) result_new = string.removeprefix(prefix) print(result_new) # Output: world! # Using slicing for older Python versions if string.startswith(prefix): result_old = string[len(prefix):] else: result_old = string print(result_old) # Output: world!
Common Pitfalls
A common mistake is to remove the prefix without checking if it exists, which can lead to incorrect results or errors. For example, slicing without startswith() can remove characters even if the prefix is not present.
Also, removeprefix() only removes the prefix if it exactly matches the start of the string; partial matches or substrings inside the string are not removed.
string = "Hello, world!" prefix = "Hi, " # Wrong way: slicing without check wrong_result = string[len(prefix):] print(wrong_result) # Output: lo, world! (incorrect) # Right way: check before slicing if string.startswith(prefix): right_result = string[len(prefix):] else: right_result = string print(right_result) # Output: Hello, world! (correct)
Quick Reference
Here is a quick summary of methods to remove a prefix from a string in Python:
| Method | Description | Python Version |
|---|---|---|
str.removeprefix(prefix) | Removes prefix if present, returns original string otherwise | 3.9+ |
Slicing with startswith() | Check prefix then slice string to remove it | All versions |
| Naive slicing without check | Can remove wrong characters if prefix not present | Not recommended |