Python String removesuffix()

Python String removesuffix() method

Python String removesuffix() method removes the specified suffix from the string, if the string ends with the specified suffix value, and returns the resulting string.

If the string does not end with the specified suffix, then the removesuffix() method returns a copy of the original string.

Consider that given string is in x.

x = "HelloWorld"

Then the return value of x.removesuffix(“World”) is

"Hello"

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

Syntax of removesuffix() method

The syntax of string removesuffix() method is:

str.removesuffix(suffix) 

You can read the above expression as: If the string str, remove suffix from the end of the string, if the string ends with the specified suffix value.

Parameters

String removesuffix() method takes only one mandatory parameter.

ParameterDescription
suffixRequired
A string value. Type: str
If the string ends with this value, then the method removes this value from the end of the string.

Return value

The String removesuffix() method returns a string value.

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

Examples

1. Remove the suffix “World” 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 suffix value “World” from the string.

Call removesuffix() on my_string, and pass the suffix value “World” as argument.

Python Program

my_string = "HelloWorld"
output_string = my_string.removesuffix("World")
print(output_string)
Run Code Copy

Output

Hello

2. Remove the suffix “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 suffix value “Apple” from the string.

Call removesuffix() on my_string, and pass the suffix value “Apple” as argument.

Python Program

my_string = "HelloWorld"
output_string = my_string.removesuffix("Apple")
print(output_string)
Run Code Copy

Output

HelloWorld

Since the original string “HelloWorld” does not end with the suffix value “Apple”, removesuffix() returned a copy of the original string.

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍