Python .removeprefix()

stuartmosquera's avatar
Published Aug 28, 2025
Contribute to Docs

The .removeprefix() method is a built-in string method that returns a new string with the specified prefix removed, if present. If the string does not start with the given prefix, the original string is returned unchanged. This method is case-sensitive and does not modify the original string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

string.removeprefix(prefix)

Parameters:

prefix: The substring to remove from the beginning of the string.

Return value:

A new string with the prefix removed if it exists, otherwise, the original string.

Example 1: Basic Prefix Removal

In this example, a matching prefix is removed from a string, or the string is left unchanged if no match is found:

original_string = "Python3.9"
result = original_string.removeprefix("Python")
result2 = original_string.removeprefix("JavaScript")
print(original_string)
print(result)
print(result2)

The code will produce this output:

Python3.9
3.9
Python3.9

Example 2: Cleaning file paths

In this example, a base directory path is stripped from a full file path to get a relative path:

base_path = "/home/user/"
absolute_file = "/home/user/project/data/file.txt"
relative_file = absolute_file.removeprefix(base_path)
print(relative_file)

The code will produce this output:

project/data/file.txt

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours