0 votes
1 view
in Python by (21.3k points)

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 Answer

0 votes
by (52.8k points)

To remove a substring from the end of a string in Python you can use endswith and slicing together below is an example that illustrates how to do it:-

url = 'abcdc.com'

if url.endswith('.com'):

url = url[:-4]

print(url)

As in the above string, we wanted to remove the last 4 characters so we did :-4 and it has erased the last 4 characters.

image

You can also remove the string using regular expressions as follows:

import re

url = 'abcdc.com'

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

print(url)

image

...