Remove the string after the # mark in a website url

We are supposed to start a new project today but because I still need a few more days to prepare for it, therefore, I have posted another question and answer session in this website just to get the thing going. This question again comes from the codewars website and it goes like this.

Given a url, stripes everything after the # mark. The solution to this question is fairly simple. If that url contains the # mark, the program will remove all the characters after the # mark and returns the new url or else the original url will be returned.

def remove_url_anchor(url):
   
    index = url.find('#')
    if(index != -1):
        return url[0:url.find('#')]
    else:
        return url

We will continue to solve more python questions until the tutorial’s material for the new project is fully ready.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
3 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Paulo AlmeidaThere are some simpler ways Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
There are some simpler ways
Guest
There are some simpler ways
Paulo Almeida
Guest
Paulo Almeida

You could also do:

from urllib.parse import urldefrag
urldefrag(url).url