Reputation: 33
I want to produce a list of possible websites from two lists:
strings = ["string1", "string2", "string3"]
tlds = ["com', "net", "org"]
to produce the following output:
string1.com
string1.net
string1.org
string2.com
string2.net
string2.org
I've got to this:
for i in strings:
print i + tlds[0:]
But I can't concatenate str and list objects. How can I join these?
Upvotes: 2
Views: 917
Reputation: 78573
One very simple way to write this is the same as in most other languages.
for s in strings:
for t in tlds:
print s + '.' + t
Upvotes: 2
Reputation: 94289
A (nested) list comprehension would be another alternative:
[s + '.' + tld for s in strings for tld in tlds]
Upvotes: 7
Reputation: 3606
The itertools
module provides a function that does this.
from itertools import product
urls = [".".join(elem) for elem in product(strings, tlds)]
The urls
variable now holds this list:
['string1.com',
'string1.net',
'string1.org',
'string2.com',
'string2.net',
'string2.org',
'string3.com',
'string3.net',
'string3.org']
Upvotes: 5
Reputation: 1741
itertools.product
is designed for this purpose.
url_tuples = itertools.product(strings, tlds)
urls = ['.'.join(url_tuple) for url_tuple in url_tuples]
print(urls)
Upvotes: 13