-1

I am trying to make this return a string by alternating the letters from the 2 strings inputted. For example, foldStrings("abc","def") should return "adbecf". This is what I have, but all it does is check if the two strings are the same length or not. I'm not really sure where to start.

    def foldStrings(string1,string2):
        x=string1
        y=string2
        if len(x)==len(y):
          return "True"
        else:
          return "The two strings are not equal in length."

It's the "True" statement that needs to be changed. Could anyone help me out?

Hawk Student
  • 147
  • 3
  • 9

2 Answers2

3

You can use zip and flatten the results:

>>> ''.join([''.join(t) for t in zip('abc','def')])
'adbecf'

Which works for more than 2 strings as well:

>>> ''.join([''.join(t) for t in zip('abc','def','xyz')])
'adxbeycfz'
dawg
  • 98,345
  • 23
  • 131
  • 206
0

You may use zip() as to iterate two list simultaneously and do join() to convert list to str as::

>>> a, b = "abc", "def"
>>> new_list = [i+j for i, j in zip(a, b)]
>>> ''.join(new_list)
'adbecf'

My personal favourite (and fastest, check stats at answer to alternately appending elements from two lists is to do it via list slicing as:

>>> n = list("abc") + list("def")  # create list
>>> n[::2], n[1::2] = a, b  # slice list alternatively
>>> ''.join(n)
'adbecf'
Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126