【问题标题】:Python merging strings in X positionsPython在X位置合并字符串
【发布时间】:2017-05-17 16:55:42
【问题描述】:

我正在研究一些 ASCII 艺术,但我有一个子问题。我想将 2 个字符串合并在一起以创建一个更大的字符串,但我想合并这些字符串,以便每隔一个字母合并,剩下的将留在它们所在的位置。所以,如果我有字符串"home""sweet",我希望输出为"hsowmeet";或更长的合并,我打算将其作为 ASCII 艺术,^^^&&&&&& 将合并到 ^&^&^&&&

我知道我要离开了,但我是这样开始的:

def merge(s1, s2):
  new = s1[1:2] + s2[1:2] + s1[2:2] + s2[2:2]
  return new

但到目前为止它看起来很丑,并没有做我想做的事

【问题讨论】:

    标签: python string merge


    【解决方案1】:

    你可以使用zip_longest:

    from itertools import zip_longest
    
    a = "^^^"
    b = "&&&&&&"
    
    def merge(a, b)
        return "".join((x+y for (x, y) in zip_longest(a, b, fillvalue="")))
    
    merge(a, b) # '^&^&^&&&&'
    

    【讨论】:

      【解决方案2】:

      您可以使用 itertools.izip_longest 和空字符串作为 fillvalue 关键字参数,然后调整返回值,直到它成为您想要的字符串。

      这是izip_longest 产生的输出(我从结果中列出了一个可读的列表):

      >>> from itertools import izip_longest
      >>> s1 = 'home'
      >>> s2 = 'sweet'
      >>> list(izip_longest(s1, s2, fillvalue=''))
      [('h', 's'), ('o', 'w'), ('m', 'e'), ('e', 'e'), ('', 't')]
      

      现在您只需连接所有字符串(长度为 1 或 0)。一种解决方案是

      >>> ''.join(sum(izip_longest(s1, s2, fillvalue=''), ()))
      'hsowmeeet'
      

      或者,只需使用常规的for 循环:

      >>> result = ''
      >>> for x,y in izip_longest(s1, s2, fillvalue=''):
      ...     result += x + y
      ... 
      >>> result
      'hsowmeeet'
      

      【讨论】:

      • 使用sum 或使用重复的+= 构建一个字符串会在创建最终结果之前创建许多中间和更大的对象。像这样的小任务可能并不重要,但值得指出的是,该算法的效率低于它需要的效率。
      【解决方案3】:
      from itertools import zip_longest
      
      def merge_words(*words):
          return ''.join(c for tup in zip_longest(*words) for c in tup if c)
      

      例子:

      >>> merge_words('abc', '123456789')
      'a1b2c3456789'
      >>> merge_words('red', 'rover')
      'rreodver'
      >>> merge_words('Python', 'merging', 'strings')
      'Pmsyettrrhgioinnnggs'
      

      注意:如果使用 Python 2,请将 zip_longest 更改为旧名称 izip_longest

      【讨论】:

        【解决方案4】:

        您可以使用itertools

        from itertools import izip_longest
        
        def merge(s1, s2):
            return ''.join([i+j for i,j in izip_longest(s1, s2, fillvalue='')])
        

        在 python 3.x 中,它是 zip_longest 而不是 izip_longest

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-20
          • 1970-01-01
          • 2021-07-23
          • 1970-01-01
          • 1970-01-01
          • 2013-07-11
          相关资源
          最近更新 更多