Python String removeprefix()


Python String removeprefix() method

Python String removeprefix() method removes the specified prefix from the string, if the string starts with the specified prefix value, and returns the resulting string.

If the string does not start with the specified prefix, then the removeprefix() method returns a copy of the original string.

Consider that given string is in x.

x = "HelloWorld"

Then the return value of x.removeprefix("Hello") is

"World"

In this tutorial, you will learn how to use string removeprefix() method to remove the specified prefix from the string.

Syntax of removeprefix() method

The syntax of string removeprefix() method is:

str.removeprefix(prefix) 

You can read the above expression as: If the string str, remove prefix from the beginning of the string, if the string starts with the specified prefix value.

Parameters

String removeprefix() method takes only one mandatory parameter.

ParameterDescription
prefixRequired
A string value. Type: str
If the string starts with this value, then the method removes this value from the beginning of the string.

Return value

The String removeprefix() method returns a string value.

The original string on which we are calling the replace() method is not modified.

Examples

1. Remove the prefix "Hello" from the string in Python

In the following example, we are given a string in my_string. In this string, we have to remove the prefix value "Hello" from the string.

Call removeprefix() on my_string, and pass the prefix value "Hello" as argument.

Python Program

my_string = "HelloWorld"
output_string = my_string.removeprefix("Hello")
print(output_string)

Output

World

2. Remove the prefix "Apple" form the string in Python

In the following example, we are give a string in my_string. In this string, we have to remove the prefix value "Apple" from the string.

Call removeprefix() on my_string, and pass the prefix value "Apple" as argument.

Python Program

my_string = "HelloWorld"
output_string = my_string.removeprefix("Apple")
print(output_string)

Output

HelloWorld

Since the original string "HelloWorld" does not start with the prefix string "Apple", removeprefix() returned a copy of the original string.

Summary

In this tutorial of Python Examples, we learned about string removeprefix() method, and how to use this string removeprefix() method to remove the specified prefix from the original string, with the help of well detailed examples.