Python String removesuffix() Method – Tutorial with Examples

Python String removesuffix() Method

The removesuffix() method is a string method in Python that is used to remove a given suffix from a string. It is similar to the removeprefix() method, but it removes the suffix of a string instead of the prefix.

Syntax

string.removesuffix(suffix)

The removesuffix() method takes a single argument:

  • suffix – the suffix to remove from the string

The removesuffix() method returns a new string with the specified suffix removed. If the string does not end with the specified suffix, the original string is returned.

Examples

Example 1: Removing a Suffix from a String

Let’s say we have a string that ends with a certain suffix and we want to remove that suffix. Here’s an example:

string = "Hello World.txt"
new_string = string.removesuffix(".txt")

print(new_string)

In this example, we start with a string that ends with the suffix “.txt”. We then use the removesuffix() method to remove that suffix and assign the result to a new string called new_string. Finally, we print the new string to the console, which should now be “Hello World”.

The output of this example should be:

Hello World

Example 2: Removing a Suffix that Doesn’t Exist

If the specified suffix does not exist at the end of the string, the original string is returned. Here’s an example:

string = "Hello World"
new_string = string.removesuffix(".txt")

print(new_string)

In this example, we start with a string that does not end with the suffix “.txt”. We then use the removesuffix() method to remove that suffix and assign the result to a new string called new_string. Finally, we print the new string to the console, which should be the same as the original string: “Hello World”.

The output of this example should be:

Hello World

Example 3: Removing Multiple Suffixes

The removesuffix() method can be used to remove multiple suffixes from a string, one at a time. Here’s an example:

string = "Hello World.txt.bak"
new_string = string.removesuffix(".bak").removesuffix(".txt")

print(new_string)

In this example, we start with a string that ends with two suffixes: “.txt” and “.bak”. We then use the removesuffix() method twice to remove each suffix one at a time. Finally, we print the new string to the console, which should be “Hello World”.

The output of this example should be:

Hello World

Use Cases

The removesuffix() method can be useful in situations where you need to remove a suffix from a string. For example, if you have a list of file names with different extensions, you can use this method to remove the extensions and get just the base file name.

Another use case could be in cleaning up data from a database or other source. If you have a string with extraneous suffixes or other text at the end, you can use this method to remove them and get just the relevant data.

Leave a Reply

Your email address will not be published. Required fields are marked *