在联接中轻松替换定界符 [英] Easily Alternate Delimiters in a Join

查看:60
本文介绍了在联接中轻松替换定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想将其他所有字符串(在此示例中为两个"字符串)包装在< strong>中.</strong> 标签.令人沮丧的是我无法执行'< strong>'.join(list),因为其他每个人都没有/.这是我能想到的唯一方法,但是使用标志使我感到困扰……而且我似乎在google机器上找不到关于此问题的任何其他信息.

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)

如果这是越野车,我深表歉意,我还是python的新手.有一个更好的方法吗?我觉得这在其他领域也很有用,例如添加左/右引号.

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.

推荐答案

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

这篇关于在联接中轻松替换定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆