removesuffix() method allows us to remove a specified suffix from a string. This method is particularly helpful when we need to work with strings and remove unwanted endings without manually checking or slicing. For example, we might have a file name that ends with ".txt" and want to remove it to get just the name of the file. We can do this easily using removesuffix().
Example:
s1 = "geeks.txt"
s2 = s1.removesuffix(".txt")
print(s2)
Output:
geeksTable of Content
Syntax of removesuffix()
str.removesuffix(suffix)Parameters:
- suffix (required): The substring that we want to remove from the end of the string.
Return Type:
- This method returns a new string with the suffix removed. If the suffix is not found at the end, it returns the original string unchanged.
Case Sensitivity in Suffix Removal
removesuffix() method is case-sensitive, meaning it will only remove the suffix if the case matches exactly. For example:
s1 = "geeky.TXT"
s2 = s1.removesuffix(".txt")
print(s2)
Output:
geeky.TXTHandling Multiple Spaces in Suffix Removal
If the suffix consists of multiple spaces, the removesuffix() method will only remove the exact number of spaces at the end of the string.
s1 = "hello geeks "
s2 = s1.removesuffix(" ")
print(s2)
Output
hello geeksHandling Unicode Characters in Suffix Removal
removesuffix() can handle strings that include Unicode characters or special characters from different languages.
s1 = "स्वागत है"
s2 = s1.removesuffix("है")
print(s2)
Output
स्वागत