Extract Domain
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a URL string containing '://', return the substring between '://' and the next '/' (or end of string if no trailing slash).
The domain is buried in the string.
Example 1
Input:
url = "https://api.example.com/v2/data"
Output:
"api.example.com"
Example 2
Input:
url = "http://localhost:8080/health"
Output:
"localhost:8080"
Worked solution and explanation
Why this problem exists in real interviews
Extracting a domain from a URL tests string splitting and indexing, a pattern that appears constantly in log parsing and ETL pipelines. It checks whether you can find substrings between delimiters efficiently.
Break down the requirements
Step 1: Find the position after ://
Split on '://' and take the part after it. This isolates everything after the protocol.
Step 2: Take everything before the next /
Split the remainder on '/' and take the first segment. This gives the domain.
The solution
def extract_domain(url):
after_protocol = url.split('://')[1]
domain = after_protocol.split('/')[0]
return domainCommon follow-up questions
- What if the URL has a port number like 'https://example.com:8080/path'? (Tests splitting on ':' after the protocol to separate domain and port.)
- How would you extract the subdomain separately? (Tests splitting the domain on '.' and taking all but the last two segments.)
- What if the URL is malformed and has no ://? (Tests error handling: return an empty string or raise a ValueError.)