Merge two strings with alternate chars as output

后端 未结 5 1334
悲哀的现实
悲哀的现实 2021-01-17 01:53

I got the task to alternately combine the letters of two strings with the same length.

For example:

Inputstring 1: \"acegi\"

Inputstring 2: \"bdfhj\         


        
5条回答
  •  青春惊慌失措
    2021-01-17 02:04

    You can do it in one line using zip and join.

    out1 = ''.join(''.join(f for f in tup) for tup in zip(inp1, inp2))
    

    or the more functional-style:

    out1 = ''.join(map(''.join, zip(inp1, inp2)))  # kudos @Coldspeed
    

    which both print

    abcdefghij
    

    Braking the code down:

    • zip()

      pairs = list(zip(inp1, inp2))
      print(pairs )  # [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', 'j')]
      
    • .join()

      temp = []
      for sub in pairs:
          temp.append(''.join(sub))
      print(temp)  # ['ab', 'cd', 'ef', 'gh', 'ij']
      
    • .join() again

      out1 = ''.join(temp)
      print(out1)  # abcdefghij
      

    Finally, and for your entertainment and learning only, two additional, more old-school approaches:

    out1 = ''
    for i in range(len(inp1)):
        out1 += inp1[i] + inp2[i]
    

    and

    out1 = ''
    for i, c in enumerate(inp1):
        out1 += c + inp2[i]
    

提交回复
热议问题