Python String removeprefix() Method



The Python string removeprefix() method is used to remove a specified prefix from the beginning of a string.

If the string starts with the specified prefix, the method removes the prefix from the string and returns the modified string. If the string does not start with the specified prefix, the method returns the original string unchanged.

Syntax

Following is the basic syntax of the Python String removeprefix() method −

string.removeprefix(prefix)

Parameter

This method accepts a string as a parameter that specifies the prefix to be removed from the beginning of the string.

Return Value

The method returns a new string with the specified prefix removed from the beginning.

Example

In the following example, we are removing the prefix "Hello " from the string "text" using the removeprefix() method −

text = "Hello World"
result = text.removeprefix("Hello ")
print(result)    

Output

The output obtained is as follows −

World

Example

This example shows that if the given prefix does not exist in the specified string, the original string is returned without any modifications −

text = "World"
result = text.removeprefix("Hello ")
print(result)      

Output

Following is the output of the above code −

World

Example

The removeprefix() method, by default, performs a case-sensitive removal. In this instance, the method does not remove the prefix "hello " from the string "text" and returns the original string instead −

text = "HELLO World"
result = text.removeprefix("hello ")
print(result) 

Output

The result produced is as shown below −

HELLO World

Example

Now, we are removing the numeric prefix "12345" from the string "text" −

text = "12345World"
result = text.removeprefix("12345")
print(result)

Output

We get the output as shown below −

World
split_and_join.htm
Advertisements