Reputation: 177
I have a list of host names as such:
testhost.my.domain.net
host2.domain.net
host3.domain.name.org
basically there can be either 2 or 3 parts in the domain name.
I need to store the host name (testhost, host2, host3) separate from the domain name (my.domain.net, domain.net, and domain.name.org) in a table which is why i am working on splitting the name.
Here is the code I have so far however it does not work because the length of the split can very.
hostname = "practice-host.my.link.com"
split = hostname.split(".")
hostname = split[0]
domain = split[1] + "." + split[2] + "." + split[3]
print (hostname, domain)
I would like to do something like this,
for i = 1, i < len(split):
domain += split[i] + "."
i += 1
but this of course won't work. Can someone offer a pythonic idea for how to achieve what i need?
Upvotes: 0
Views: 1469
Reputation: 114310
You have
name = 'testhost.my.domain.net'
split = name.split('.')
You can get the host as the first element:
host = split[0]
The domain can be recombined with the inverse of split
, which is join
:
domain = '.'.join(split[1:])
Another way to do it is to only split off on the first occurrence of .
:
host, domain = name.split('.', 1)
This version is arguably cleaner but less robust against missing name elements.
Upvotes: 1
Reputation: 2652
split
takes a second argument, maxsplit
, which you could set to 1
:
domains = [
"testhost.my.domain.net",
"host2.domain.net",
"host3.domain.name.org"
]
split_domains = [d.split(".", 1) for d in domains]
Which will give you:
[
['testhost', 'my.domain.net'],
['host2', 'domain.net'],
['host3', 'domain.name.org']
]
Which is what I think you’re looking for.
Upvotes: 2
Reputation: 113978
hostname = "www.qq1.com"
domain_name = ".".join(hostname.rsplit(".",2)[-2:])
I guess is what you are asking for?
Upvotes: 0