Monday, November 18, 2024
Google search engine
HomeLanguagesPython String – removeprefix() function

Python String – removeprefix() function

Python String removeprefix() function removes the prefix and returns the rest of the string. If the prefix string is not found, then it returns the original string. It is introduced in Python 3.9.0 version.

Python String removeprefix() Method Syntax

Syntax: str_obj_name.removeprefix(prefix

Parameters: prefix– prefix string that we are checking for.

Return: Returns the copy of the string with the prefix removed(if present), else the original string.

Python String removeprefix() Method Example

Python3




new_string = 'Lazyroar'.removeprefix("Geeksfor")
print(new_string)


Output:

Geeks

Example 1: Basic usage of Python String removeprefix() Method

We can remove a prefix string from a string using Python String removeprefix() Method. If the prefix is not the prefix in the string, the original string is returned.

Python3




s = 'Lazyroar'
 
# prefix exists
print(s.removeprefix('Geeks'))
print(s.removeprefix('G'))
 
 
# whole string is a prefix
# it would print an empty string
print(s.removeprefix('Lazyroar'))
 
# prefix doesn't exist
# whole string is returned
print(s.removeprefix('for'))
print(s.removeprefix('IT'))
print(s.removeprefix('forGeeks'))


Output:

forGeeks
eeksforGeeks

Lazyroar
Lazyroar
Lazyroar

Example 2: More Examples on Python String removeprefix() Method

If a prefix exists, then Python String removeprefix() Method remove the prefix from the string, otherwise return the original string.

Python3




string1 = "Welcome to python 3.9"
print("Original String 1 : ", string1)
   
# prefix exists
result = string1.removeprefix("Welcome")
print("New string : ", result)
   
string2 = "Welcome Geek"
print("Original String 2 : ", string2)
   
# prefix doesn't exist
result = string2.removeprefix("Geek")
print("New string : ", result)


Output:

Original String 1 :  Welcome to python 3.9
New string :   to python 3.9
Original String 2 :  Welcome Geek
New string :  Welcome Geek

RELATED ARTICLES

Most Popular

Recent Comments