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


Question

I have the following code:

url = 'abcdc.com'
print(url.strip('.com'))

I expected: abcdc

I got: abcd

Now I do

url.rsplit('.com', 1)

Is there a better way?

1
314
4/9/2015 7:54:30 PM

Accepted Answer

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 the ends of x.

Instead, you could use endswith and slicing:

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

Or using regular expressions:

import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
470
7/21/2018 11:53:14 PM

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

url = 'abcdc.com'
print(url.replace('.com',''))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon