Better way of replacing subtring from a string

I’m new to python and looking for a better or faster solution.
I replaced substring from string using this solution.

In this example, that is to replace from a url string

site2 = ''
url = ''

output = site2 + url[url.index('vehicles/'):] 
print(output) #

Is this a faster solution? Is there a better one? what about using regex perhaps?

>Solution :

When manipulating structures such as URLs it’s better to use tools designed for the purpose rather than treating them as strings.

In this case you want to change the host (netloc) to


from urllib.parse import urlparse, urlunparse

new_site = ''
url = ''
scheme, _, path, params, query, fragment = urlparse(url)
new_url = urlunparse((scheme, new_site, path.replace('//', '/'), params, query, fragment))


Leave a Reply