加入中容易交替的分隔符

时间:2012-04-22 19:31:10

标签: python string delimiter implode

我有一个像这样的元组列表(字符串是填充程序......我的实际代码具有未知值):

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

我想在<strong> </strong>标记中包装所有其他字符串(在此示例中为&#39;两个&#39;字符串)。令我感到沮丧的是,我无法'<strong>'.join(list),因为其他每个人都没有/。这是我能想到的唯一方法,但是使用旗帜困扰着我...而且我似乎无法在谷歌机器上找到关于此问题的任何其他内容。

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)

如果这是错误的,我道歉,我还是python的新手。有一个更好的方法吗?我觉得这在其他方面也很有用,就像添加左/右引号一样。

5 个答案:

答案 0 :(得分: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']

答案 1 :(得分:4)

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您可以应用比“彼此”更复杂的模式。

答案 2 :(得分:1)

比unbeli的回答略微更加Pythonic:

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

答案 3 :(得分:1)

@jhibberd's answer很好,但为了以防万一,这里没有导入相同的想法:

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)]

答案 4 :(得分:0)

您也可以使用enumerate。对我来说它看起来更干净。

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