str.removeprefix()
Added in v3.9 · Updated March 13, 2026 · String Methods
stdlib string methods
The .removeprefix() method returns a copy of the string with the prefix removed, if the string actually starts with that prefix. If the prefix is not present, the method returns a copy of the original string unchanged. This method was added in Python 3.9 as part of PEP 616.
Signature
str.removeprefix(prefix)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
prefix | str | Required | The prefix string to remove from the beginning |
Return Value
Returns a new string with the prefix removed. The original string remains unchanged.
Basic Examples
Remove a matching prefix
text = "HelloWorld"
result = text.removeprefix("Hello")
print(result) # Output: World
Prefix not present returns unchanged string
text = "PythonProgramming"
result = text.removeprefix("Java")
print(result) # Output: PythonProgramming
Case-sensitive matching
text = "PythonProgramming"
result = text.removeprefix("python")
print(result) # Output: PythonProgramming
Practical Use Cases
Cleaning API responses
# API returns data prefixed with namespace
response = "api_user_12345"
user_id = response.removeprefix("api_")
print(user_id) # Output: user_12345
Handling file paths
# Remove base directory from full path
full_path = "/home/user/project/src/main.py"
relative = full_path.removeprefix("/home/user/")
print(relative) # Output: project/src/main.py
Normalizing input
# Remove common prefixes from product codes
codes = ["SKU-001", "SKU-002", "SKU-003"]
for code in codes:
print(code.removeprefix("SKU-"))
# Output:
# 001
# 002
# 003
Chaining with other string methods
# Remove prefix then convert to uppercase
text = "hello_world"
result = text.removeprefix("hello_").upper()
print(result) # Output: WORLD
Common Patterns
Working with empty prefix
Passing an empty string as the prefix returns a copy of the original string:
text = "Hello"
result = text.removeprefix("")
print(result) # Output: Hello
This behavior can be useful in generalized string processing functions where the prefix might be optional.
Combining with conditional logic
You can use the method with conditional checks when you need different behavior based on whether the prefix exists:
def process_identifier(id_string, namespace):
if id_string.startswith(namespace + "_"):
return id_string.removeprefix(namespace + "_")
return id_string
print(process_identifier("user_123", "user")) # Output: 123
print(process_identifier("order_456", "user")) # Output: order_456
Behavior Notes
- The method is case-sensitive. Use
.casefold()or.lower()first if you need case-insensitive prefix removal. - If the string does not start with the specified prefix, the original string is returned unchanged.
- The method always returns a new string—it never modifies the original in place.
- For removing suffixes instead, see
.removesuffix()which was added alongside this method in Python 3.9.