Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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
1 answer
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
2 answers
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...