How to Remove a Suffix from a String in Python?

Estimated read time 1 min read

To remove a suffix from a string in Python, you can use the str.endswith() method to check if the string ends with the suffix, and then use string slicing to remove it. Here’s an example:

# Remove a suffix from a string
my_string = "example.txt"
suffix = ".txt"
if my_string.endswith(suffix):
    new_string = my_string[:-len(suffix)]
    new_string = my_string
print(new_string)  # Output: example

In this example, we define a string my_string and a suffix to remove suffix. We use the str.endswith() method to check if my_string ends with suffix. If it does, we create a new string new_string that contains all the characters of my_string except for the len(suffix) characters at the end. If my_string does not end with suffix, we set new_string to my_string unchanged.

Note that the str.endswith() method is case-sensitive by default. If you want to make it case-insensitive, you can convert both my_string and suffix to lowercase or uppercase before calling str.endswith().

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply