【问题标题】:Easily Alternate Delimiters in a Join在连接中轻松替换分隔符
【发布时间】:2012-04-22 19:31:10
【问题描述】:

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

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

我想将所有其他字符串(在本例中为“两个”字符串)包装在 <strong> </strong> 标记中。令人沮丧的是我不能做'<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 新手。有一个更好的方法吗?我觉得这在其他领域也很有用,比如添加左/右引号。

【问题讨论】:

    标签: python string delimiter implode


    【解决方案1】:
    >>> 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']
    

    【讨论】:

    • 即将写相同的答案:)
    【解决方案2】:
    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,您可以应用比“其他”更复杂的模式。

    【讨论】:

      【解决方案3】:

      比 unbeli 的回答更 Pythonic:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多