Python program to delete suffix from the given string

In Python, we have several built-in string methods like endswith(), rstrip(), and replace() that can be used to delete suffixes from strings. A suffix is a group of characters at the end of a string that we want to remove. For example, removing "NING" from "BRIGHTNING" gives us "BRIGHT".

Common Methods for Suffix Removal

endswith() Method

This method checks if a string ends with a specified suffix and returns True or False ?

text = "programming"
print(text.endswith("ming"))  # True
print(text.endswith("code"))  # False
True
False

rstrip() Method

This method removes specified characters from the end of a string ?

text = "programming"
result = text.rstrip("ming")
print(result)
program

replace() Method

This method replaces all occurrences of a substring with another string ?

text = "programming"
if text.endswith("ming"):
    result = text.replace("ming", "")
    print(result)
program

Method 1: Using String Slicing with endswith()

Remove suffix by slicing the string to exclude the suffix length ?

text = "RANSOMEWARE"
suffix = "WARE"

if text.endswith(suffix):
    result = text[:-len(suffix)]
    print("After deleting the suffix:", result)
else:
    print("Suffix not found")
After deleting the suffix: RANSOME

Method 2: Using Length Calculation

Calculate the new string length by subtracting the suffix length ?

text = "Doctorate"
suffix = "ate"

if text.endswith(suffix):
    result = text[:len(text) - len(suffix)]
    print("After deleting the suffix:", result)
else:
    print("Suffix not found")
After deleting the suffix: Doctor

Method 3: Using rstrip()

The rstrip() method removes characters from the right end of the string ?

text = "Rectangle"
result = text.rstrip("gle")
print("After deleting the suffix:", result)
After deleting the suffix: Rectan

Method 4: Using replace() with Condition

Use replace() method with endswith() to ensure we only remove the suffix ?

text = "abcdefghi"
suffix = "ghi"

if text.endswith(suffix):
    result = text.replace(suffix, "")
    print("After deleting the suffix:", result)
else:
    print("Suffix not found")
After deleting the suffix: abcdef

Comparison of Methods

Method Pros Cons Best For
String Slicing Simple, efficient Requires length calculation Known suffix lengths
rstrip() Very concise Removes all matching characters Character removal
replace() Clear intent Replaces all occurrences Specific substring removal

Conclusion

Use string slicing with endswith() for precise suffix removal. The rstrip() method works well for character removal, while replace() is useful when combined with conditional checks. Choose the method that best fits your specific use case.

---
Updated on: 2026-03-27T07:05:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements