Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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

Related questions

0 votes
1 answer
0 votes
2 answers
+2 votes
3 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...