In Python 3.9 and later, dedicated methods removeprefix() and removesuffix() were added to remove specific prefixes and suffixes from strings.
Previously, lstrip(), rstrip(), or slicing functionality were used for string trimming. However, these methods carried the risk of deleting unintended characters and often resulted in code that was difficult to read. By using these new methods, you can remove unnecessary text more intuitively and safely.
Table of Contents
- Method Features
- Implementation Example: Normalizing Product Codes
- Important Note: Differences from lstrip / rstrip
Method Features
str.removeprefix(prefix): If the string starts with the specifiedprefix, it returns a new string with that prefix removed. If there is no match, it returns the original string as is.str.removesuffix(suffix): If the string ends with the specifiedsuffix, it returns a new string with that suffix removed. If there is no match, it returns the original string as is.
Implementation Example: Normalizing Product Codes
Below is an example of code that normalizes a product code containing a “prefix” and “suffix” (obtained from a database or API) into a pure ID number.
def main():
# Decorated product code assigned by a system
raw_product_code = "PROD_987654_v2"
print(f"Original Code: {raw_product_code}")
# 1. Remove the leading 'PROD_' (removeprefix)
# It is removed only if the string starts with "PROD_".
# Note: This will not work in Python versions older than 3.9.
code_step1 = raw_product_code.removeprefix("PROD_")
print(f"After prefix removal: {code_step1}")
# 2. Remove the trailing '_v2' (removesuffix)
# It is removed only if the string ends with "_v2".
clean_id = code_step1.removesuffix("_v2")
print(f"After suffix removal: {clean_id}")
# --- Note: Behavior when there is no match ---
# If the specified string is not found, the original string is returned.
no_change = raw_product_code.removeprefix("UNKNOWN_")
print(f"No match case: {no_change}")
if __name__ == "__main__":
main()
Important Note: Differences from lstrip / rstrip
The traditional lstrip() and rstrip() methods remove “any character included in the specified set.” If you use them with the intention of removing a specific word, it can cause unintended behavior.
Incorrect Usage Example (using lstrip):
# Instead of removing the string "PROD_",
# it removes any of the characters 'P', 'R', 'O', 'D', '_' found at the start.
text = "PROD_D001"
print(text.lstrip("PROD_"))
# Result: "001"
# (Expected "D001", but 'D' was also removed because it is in "PROD_")
In contrast, removeprefix only performs the deletion if the entire string matches exactly, preventing accidents like the one above.
If you are working in a Python 3.9+ environment, using removeprefix and removesuffix is recommended for both readability and safety.
