[Solved] Better way of replacing subtring from a string [duplicate]


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 www.site2.com

So…

from urllib.parse import urlparse, urlunparse

new_site="www.site2.com"
url="https://www.site1.com//vehicles/2023/Ford/F-150/Calgary/AB/57506598/?sale_class=New"
scheme, _, path, params, query, fragment = urlparse(url)
new_url = urlunparse((scheme, new_site, path.replace('//', "https://stackoverflow.com/"), params, query, fragment))
print(new_url)

Output:

https://www.site2.com/vehicles/2023/Ford/F-150/Calgary/AB/57506598/?sale_class=New

1

solved Better way of replacing subtring from a string [duplicate]