Open In App

Python String – removesuffix()

If the string ends with the suffix and the suffix is not empty, the str.removesuffix(suffix, /) function removes the suffix and returns the rest of the string. If the suffix string is not found then it returns the original string. It is introduced in Python 3.9.0 version.



Syntax: str.removesuffix(suffix, /)

Parameters:



Suffix– suffix string that we are checking for.

Return value:

Returns: string[ : – len (suffix) ] if the string ends with suffix string and that suffix is not empty. Else it returns the copy of original string.

Example 1:




# Python 3.9 code explaining
# str.removesuffix()
  
# suffix exists
print('ComputerScience'.removesuffix('Science'))
  
# suffix doesn't exist
print('GeeksforGeeks'.removesuffix('for'))

Output:

Computer
GeeksforGeeks

Example 2:




# Python 3.9 code explaining
# str.removesuffix()
  
# String for removesuffix()
# If suffix exists then
# then it remove suffix from the string
# otherwise return original string
  
string1 = "Welcome to python 3.9"
print("Original String 1 : ", string1)
  
# suffix exists
result = string1.removesuffix("3.9")
print("New string : ", result)
  
string2 = "Welcome Geek"
print("Original String 2 : ", string2)
  
# suffix doesn't exist
result = string2.removesuffix("Welcome")
print("New string : ", result)

Output:

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

Article Tags :