4

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Cassie
  • 292
  • 1
  • 3
  • 9

5 Answers5

6
>>> 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']
unbeli
  • 29,501
  • 5
  • 55
  • 57
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']))]

Using cycle you can apply to more complex patterns than "every other".

jhibberd
  • 7,466
  • 1
  • 16
  • 9
2

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

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)]
Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
1

Slightly more Pythonic than unbeli's answer:

item = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % elem if i % 2 else elem for i, elem in enumerate(item)]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You can use enumerate too. To me it just look cleaner.

tuple = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % x if i%2 else x for i, x in enumerate(tuple)]
Jeff
  • 6,932
  • 7
  • 42
  • 72