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

The Question :

421 people think this question is useful

I have the following code:

url = ''

I expected: abcdc

I got: abcd

Now I do

url.rsplit('.com', 1)

Is there a better way?

The Question Comments :
  • strip strips the characters given from both ends of the string, in your case it strips “.”, “c”, “o” and “m”.
  • It will also remove those characters from the front of the string. If you just want it to remove from the end, use rstrip()
  • Yeah. str.strip doesn’t do what you think it does. str.strip removes any of the characters specified from the beginning and the end of the string. So, “acbacda”.strip(“ad”) gives ‘cbac’; the a at the beginning and the da at the end were stripped. Cheers.
  • Plus, this removes the characters in any order: “site.ocm” > “site”.
  • @scvalex, wow just realised this having used it that way for ages – it’s dangerous because the code often happens to work anyway

The Answer 1

615 people think this answer is useful

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)

The Answer 2

100 people think this answer is useful

If you are sure that the string only appears at the end, then the simplest way would be to use ‘replace’:

url = ''

The Answer 3

53 people think this answer is useful

Since it seems like nobody has pointed this on out yet:

url = ""
new_url = url[:url.rfind(".")]

This should be more efficient than the methods using split() as no new list object is created, and this solution works for strings with several dots.

The Answer 4

53 people think this answer is useful
def strip_end(text, suffix):
    if suffix and text.endswith(suffix):
        return text[:-len(suffix)]
    return text

The Answer 5

27 people think this answer is useful

Depends on what you know about your url and exactly what you’re tryinh to do. If you know that it will always end in ‘.com’ (or ‘.net’ or ‘.org’) then


is the quickest solution. If it’s a more general URLs then you’re probably better of looking into the urlparse library that comes with python.

If you on the other hand you simply want to remove everything after the final ‘.’ in a string then


will work. Or if you want just want everything up to the first ‘.’ then try


The Answer 6

22 people think this answer is useful

Starting in Python 3.9, you can use removesuffix instead:

# 'abcdc'

The Answer 7

15 people think this answer is useful

If you know it’s an extension, then

url = ''
url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split

This works equally well with or or abcdc.[anything] and is more extensible.

The Answer 8

13 people think this answer is useful

In one line:

text if not text.endswith(suffix) or len(suffix) == 0 else text[:-len(suffix)]

The Answer 9

8 people think this answer is useful

How about url[:-4]?

The Answer 10

6 people think this answer is useful

For urls (as it seems to be a part of the topic by the given example), one can do something like this:

import os
url = ''
name,ext = os.path.splitext(url)
print (name, ext)

ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)

Both will output: ('http://www.stackoverflow', '.com')

This can also be combined with str.endswith(suffix) if you need to just split “.com”, or anything specific.

The Answer 11

6 people think this answer is useful

DSCLAIMER This method has a critical flaw in that the partition is not anchored to the end of the url and may return spurious results. For example, the result for the URL “” is “www” (incorrect) instead of the expected “”. This solution therefore is evil. Don’t use it unless you know what you are doing!


This is fairly easy to type and also correctly returns the original string (no error) when the suffix ‘.com’ is missing from url.

The Answer 12

4 people think this answer is useful

If you mean to only strip the extension:

# 'abcdc'

It works with any extension, with potential other dots existing in filename as well. It simply splits the string as a list on dots and joins it without the last element.

The Answer 13

3 people think this answer is useful

Assuming you want to remove the domain, no matter what it is (.com, .net, etc). I recommend finding the . and removing everything from that point on.

url = ''
dot_index = url.rfind('.')
url = url[:dot_index]

Here I’m using rfind to solve the problem of urls like which should be reduced to the name

If you’re also concerned about www.s, you should explicitly check for them:

if url.startswith("www."):
   url = url.replace("www.","", 1)

The 1 in replace is for strange edgecases like

If your url gets any wilder than that look at the regex answers people have responded with.

The Answer 14

3 people think this answer is useful

If you need to strip some end of a string if it exists otherwise do nothing. My best solutions. You probably will want to use one of first 2 implementations however I have included the 3rd for completeness.

For a constant suffix:

def remove_suffix(v, s):
    return v[:-len(s)] if v.endswith(s) else v
remove_suffix("", ".com") == 'abc'
remove_suffix("abc", ".com") == 'abc'

For a regex:

def remove_suffix_compile(suffix_pattern):
    r = re.compile(f"(.*?)({suffix_pattern})?$")
    return lambda v: r.match(v)[1]
remove_domain = remove_suffix_compile(r"\.[a-zA-Z0-9]{3,}")
remove_domain("") == "abc"
remove_domain("") == ""
remove_domain("abc.") == "abc."
remove_domain("abc") == "abc"

For a collection of constant suffixes the asymptotically fastest way for a large number of calls:

def remove_suffix_preprocess(*suffixes):
    suffixes = set(suffixes)
    except KeyError:

    def helper(suffixes, pos):
        if len(suffixes) == 1:
            suf = suffixes[0]
            l = -len(suf)
            ls = slice(0, l)
            return lambda v: v[ls] if v.endswith(suf) else v
        si = iter(suffixes)
        ml = len(next(si))
        exact = False
        for suf in si:
            l = len(suf)
            if -l == pos:
                exact = True
                ml = min(len(suf), ml)
        ml = -ml
        suffix_dict = {}
        for suf in suffixes:
            sub = suf[ml:pos]
            if sub in suffix_dict:
                suffix_dict[sub] = [suf]
        if exact:
            del suffix_dict['']
            for key in suffix_dict:
                suffix_dict[key] = helper([s[:pos] for s in suffix_dict[key]], None)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v[:pos])
            for key in suffix_dict:
                suffix_dict[key] = helper(suffix_dict[key], ml)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v)
    return helper(tuple(suffixes), None)
domain_remove = remove_suffix_preprocess(".com", ".net", ".edu", ".uk", '.tv', '', '')

the final one is probably significantly faster in pypy then cpython. The regex variant is likely faster than this for virtually all cases that do not involve huge dictionaries of potential suffixes that cannot be easily represented as a regex at least in cPython.

In PyPy the regex variant is almost certainly slower for large number of calls or long strings even if the re module uses a DFA compiling regex engine as the vast majority of the overhead of the lambda’s will be optimized out by the JIT.

In cPython however the fact that your running c code for the regex compare almost certainly outweighs the algorithmic advantages of the suffix collection version in almost all cases.


The Answer 15

3 people think this answer is useful

Because this is a very popular question i add another, now available, solution. With python 3.9 ( the function removesuffix() will be added (and removeprefix()) and this function is exactly what was questioned here.

url = ''



PEP 616 ( shows how it will behave (it is not the real implementation):

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
        return self[:]

and what benefits it has against self-implemented solutions:

  1. Less fragile: The code will not depend on the user to count the length of a literal.

  2. More performant: The code does not require a call to the Python built-in len function nor to the more expensive str.replace() method.

  3. More descriptive: The methods give a higher-level API for code readability as opposed to the traditional method of string slicing.

The Answer 16

2 people think this answer is useful
import re

def rm_suffix(url = '', suffix='\.com'):
    return(re.sub(suffix+'$', '', url))

I want to repeat this answer as the most expressive way to do it. Of course, the following would take less CPU time:

def rm_dotcom(url = ''):
    return(url[:-4] if url.endswith('.com') else url)

However, if CPU is the bottle neck why write in Python?

When is CPU a bottle neck anyway? In drivers, maybe.

The advantages of using regular expression is code reusability. What if you next want to remove ‘.me’, which only has three characters?

Same code would do the trick:

>>> rm_sub('','.me')

The Answer 17

1 people think this answer is useful

In my case I needed to raise an exception so I did:

class UnableToStripEnd(Exception):
    """A Exception type to indicate that the suffix cannot be removed from the text."""

    def get_exception(text, suffix):
        return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
                                .format(suffix, text))

def strip_end(text, suffix):
    """Removes the end of a string. Otherwise fails."""
    if not text.endswith(suffix):
        raise UnableToStripEnd.get_exception(text, suffix)
    return text[:len(text)-len(suffix)]

The Answer 18

1 people think this answer is useful

You can use split:

# 'abccomputer'

The Answer 19

1 people think this answer is useful

A broader solution, adding the possibility to replace the suffix (you can remove by replacing with the empty string) and to set the maximum number of replacements:

def replacesuffix(s,old,new='',limit=1):
    String suffix replace; if the string ends with the suffix given by parameter `old`, such suffix is replaced with the string given by parameter `new`. The number of replacements is limited by parameter `limit`, unless `limit` is negative (meaning no limit).

    :param s: the input string
    :param old: the suffix to be replaced
    :param new: the replacement string. Default value the empty string (suffix is removed without replacement).
    :param limit: the maximum number of replacements allowed. Default value 1.
    :returns: the input string with a certain number (depending on parameter `limit`) of the rightmost occurrences of string given by parameter `old` replaced by string given by parameter `new`
    if s[len(s)-len(old):] == old and limit != 0:
        return replacesuffix(s[:len(s)-len(old)],old,new,limit-1) + new
        return s

In your case, given the default arguments, the desired result is obtained with:

>>> 'abcdc'

Some more general examples:

>>> 'whatever-qweNN'

>>> 'whatever-NNN'

replacesuffix('12.53000','0',' ',-1)
>>> '12.53   '

The Answer 20

0 people think this answer is useful

This is a perfect use for regular expressions:

>>> import re
>>> re.match(r"(.*)\.com", "").group(1)

The Answer 21

0 people think this answer is useful

Here,i have a simplest code.


The Answer 22

0 people think this answer is useful

Python >= 3.9:


Python < 3.9:

def remove_suffix(text, suffix):
    if text.endswith(suffix):
        text = text[:-len(suffix)]
    return text

remove_suffix('', '.com')

The Answer 23

-2 people think this answer is useful

I used the built-in rstrip function to do it like follow:

string = ""
suffix = ".com"
newstring = string.rstrip(suffix)

Add a Comment