Last modified: Oct 04, 2023 By Alexander Williams

Python: Get Domain from Subdomain [Examples]

Example 1: Using `split()` Method

# Split the subdomain by dots
subdomain = "blog.example.com"
parts = subdomain.split(".")
# Extract the domain from the parts
domain = ".".join(parts[-2:])
print("Domain:", domain)

Output:

Domain: example.com

Example 2: Using `urllib.parse` Module

from urllib.parse import urlparse

# Parse the subdomain using urlparse
subdomain = "blog.example.com"
parsed_url = urlparse(f"http://{subdomain}")
# Extract the domain from the netloc attribute
domain = parsed_url.netloc
print("Domain:", domain)

Output:

Domain: blog.example.com

Example 3: Using Regular Expressions

import re

# Use regular expressions to extract the domain
subdomain = "blog.example.com"
match = re.search(r"[\w-]+\.[a-z]{2,}", subdomain)
if match:
    domain = match.group()
    print("Domain:", domain)
else:
    print("Domain not found")

Output:

Domain: example.com