typestar

Parsing URLs in Python

Taking URLs apart and putting query strings together.

from urllib.parse import urlparse, parse_qs, urlencode, urljoin

url = "https://typestar.io/practice?lang=python&theme=monokai"
parts = urlparse(url)
host = parts.netloc
path = parts.path
params = parse_qs(parts.query)
lang = params["lang"][0]

query = urlencode({"lang": "rust", "duration": 300})
next_url = f"{parts.scheme}://{host}{path}?{query}"
absolute = urljoin(url, "/profile")

How it works

  1. urlparse splits scheme, host, path, and query.
  2. parse_qs turns the query into a dict.
  3. urlencode and urljoin rebuild URLs.

The run, in numbers

Lines
12
Characters to type
385
Tokens
103
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 4 of 4 in Web, step 13 of 41 in Domain tools.

← Previous Next →