Ramya Ramya - 2 months ago 5
Python Question

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

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?

Answer

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)
Comments