Easily alternate delimiters in combination

I have a list of tuples like this (strings are fillers ... my actual code has unknown values ​​for them):

list = [
  ('one', 'two', 'one'),
  ('one', 'two', 'one', 'two', 'one'),
  ('one', 'two', 'one', 'two', 'one', 'two', 'one'...)
]

I would like to wrap every other line (in this example, two lines) in tags <strong> </strong>. This is frustrating for what I cannot do '<strong>'.join(list), because each other will not. This is the only approach I can think of, but using the flag bothers me ... and I cannot 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)

Sorry if this is a mistake, I'm still new to python. Is there a better way to do this? I feel this may be useful in other areas, as well as adding to left / right quotes.

+3
source share
5
>>> 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']
+5
from itertools import cycle
xs = ('one', 'two', 'one', 'two', 'one')
print [t % x for x, t in zip(xs, cycle(['<strong>%s</strong>', '%s']))]

cycle, , " ".

+4

Pythonic, unbeli:

item = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % elem if i % 2 else elem for i, elem in enumerate(item)]
+1
source

@jhibberd's answer is fine, but just in case, here's the same idea without importing:

a = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
formats = ['%s', '<strong>%s</strong>']
print [formats[n % len(formats)] % s for n, s in enumerate(a)]
+1
source

You can also use enumerate. It just looks cleaner to me.

tuple = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % x if i%2 else x for i, x in enumerate(tuple)]
0
source

All Articles