Reputation: 465
I have two lists of strings that I want to join into string. Basically if I have two lists:
name = ['Name1', 'Name2', 'Name3']
link = ['Link1', 'Link2', 'Link3']
and I want to insert them into a string, such as one below:
<a href="%s">%s
Is this possible to do using join or do I need to use a for loop?
Upvotes: 0
Views: 958
Reputation: 12218
@Ignacio's answer is a great one for this application.
Depending on the intended use, you might instead need to create one string with the right number of placeholders.
from itertools import chain, izip
name = ['Name1', 'Name2', 'Name3']
link = ['Link1', 'Link2', 'Link3']
args = [i for i in chain.from_iterable(izip(name, link))]
placeholder = ''.join(["<a href=%s>%s"] * len (name))
# combined to make '<a href=%s>%s<a href=%s>%s<a href=%s>%s'
print placeholder % tuple(args)
The two useful tricks (a) to use list multiplication to duplicate the placeholder string as needed and (b) remember that % requires a tuple argument. This is a common pattern when expanding lists of placeholders
Upvotes: 0
Reputation: 799044
['<a href="%s">%s' % (n, l) for (n, l) in zip(name, link)]
But don't forget to encode n
and l
appropriately in order to prevent security issues.
Upvotes: 3