Ramya Ramya - 10 months ago 38
Python Question

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

I have the following code:

url = 'abcdc.com'

I expected:

I got:

Now I do

url.rsplit('.com', 1)

Is there a better way?

Answer Source

You could do this:

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

Or using regular expressions:

import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)