'Python modify the path of url without hacky string interpolation [closed]

How to use urllib.parse in python to modify the path of URI? I know I can use substring and index but I am wondering what is the right way to accomplish this.

Convert this:

https://foo.blob.bar.storage.azure.net/container/blobname?sv=2015-04-05&ss=123&srt=abc&sp=efg&se=2022&sig=wsx

To this:

https://foo.blob.bar.storage.azure.net/container?sv=2015-04-05&ss=123&srt=abc&sp=efg&se=2022&sig=wsx



Solution 1:[1]

If you're just trying to remove /blobname from the URL, you can simply use:

url = 'https://foo.blob.bar.storage.azure.net/container/blobname?sv=2015-04-05&ss=123&srt=abc&sp=efg&se=2022&sig=wsx'
new_url = url.replace('/blobname', '')

However, if you really want to parse the URL and reconstruct it (let's say you want to go up one directory in the URL path), you can do this:

from urllib.parse import urlparse, urlunparse
from pathlib import Path

url = 'https://foo.blob.bar.storage.azure.net/container/blobname?sv=2015-04-05&ss=123&srt=abc&sp=efg&se=2022&sig=wsx'

u = urlparse(url)
url_parts = list(u)   # Need to convert to list to update the path item
url_parts[2] = str(Path(u.path).parent)   # Using Path lib to go to the parent path
new_url = urlunparse(url_parts)  # create a new URL 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1