I have a list of tuples like so (the strings are fillers... my actual code has unknown values for these):
list = [
('one', 'two', 'one'),
('one', 'two', 'one', 'two', 'one'),
('one', 'two', 'one', 'two', 'one', 'two', 'one'...)
]
I would like to wrap every other string (in this example, the 'two' strings) in <strong> </strong>
tags. It's frustrating that I can't do '<strong>'.join(list)
because every other one won't have the /. This is the only approach I can think of but the use of the flag bothers me... and I can't seem to find anything else on the google machine about this problem.
def addStrongs(tuple):
flag = False
return_string = ""
for string in tuple:
if flag :
return_string += "<strong>"
return_string += string
if flag :
return_string += "</strong>"
flag = not flag
return return_string
formatted_list = map(addStrongs, list)
I apologize if this is buggy, I'm still new to python. Is there a better way to do this? I feel like this could be useful in other areas too like adding in left/right quotes.
>>> tuple = ('one', 'two', 'one', 'two', 'one')
>>> ['<strong>%s</strong>' % tuple[i] if i%2 else tuple[i] for i in range(len(tuple))]
['one', '<strong>two</strong>', 'one', '<strong>two</strong>', 'one']
from itertools import cycle
xs = ('one', 'two', 'one', 'two', 'one')
print [t % x for x, t in zip(xs, cycle(['<strong>%s</strong>', '%s']))]
Using cycle
you can apply to more complex patterns than "every other".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With