How to generate substrings of a dot-separated string?

Viewed 95

I am struggling to generate a list of substrings from a given list of strings.

I have a list of domains -

domains = ["abc.pqr.com", "pqr.yum.abc.com"]

Now, for each domain in the list I want to generate subdomains.

For example the subdomains of domain "abc.pqr.com" would be

["pqr.com", "abc.pqr.com"]

Also, for domain "pqr.yum.abc.com" the subdomains would be

["yum.abc.com", "pqr.yum.abc.com", "abc.com"]

So the out put of the method would be -

["yum.abc.com", "pqr.yum.abc.com", "abc.com", "pqr.com", "abc.pqr.com"]
3 Answers

First you have to iterate on elements then split your element by the '.' seperator. After that in order to keep the 'com' element intact, we iterate on the range - 1. After creating every alternative, we join the result again with the seperator "."

domains = ["abc.pqr.com", "pqr.yum.abc.com"]
domains_new = []
for d in domains:
    liste = d.split(".")
    for i in range(len(liste)-1):
        domains_new.append(liste[i:])
domains_new = [".".join(ele) for ele in domains_new]
domains_new

output:

['abc.pqr.com', 'pqr.com', 'pqr.yum.abc.com', 'yum.abc.com', 'abc.com']

Assuming the domains only contain simple tlds like .com and no second-level domains like .co.uk, you can use a python list comprehension.

[domain.split(".", x)[-1] for domain in domains for x in range(domain.count("."))] 
Related