Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily Alternate Delimiters in a Join

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.

like image 432
Cassie Avatar asked Sep 13 '25 04:09

Cassie


2 Answers

>>> 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']
like image 161
unbeli Avatar answered Sep 15 '25 17:09

unbeli


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".

like image 36
jhibberd Avatar answered Sep 15 '25 19:09

jhibberd