How do I remove a substring from the end of a string?


I have the following code:

url = ""

I expected: abcdc

I got: abcd

Now I do

url.rsplit(".com", 1)

Is there a better way?

Answer rating: 689

strip doesn"t mean "remove this substring". x.strip(y) treats y as a set of characters and strips any characters in that set from both ends of x.

On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string:

url = ""
url.removesuffix(".com")    # Returns "abcdc"
url.removeprefix("abcdc.")  # Returns "com"

The relevant Python Enhancement Proposal is PEP-616.

On Python 3.8 and older you can use endswith and slicing:

url = ""
if url.endswith(".com"):
    url = url[:-4]

Or a regular expression:

import re
url = ""
url = re.sub(".com$", "", url)

Get Solution for free from DataCamp guru