Printar 2 interlaced strings

Asked

Viewed 204 times

1

How do I print 2 interlaced strings (I don’t know if that’s what it’s called)? For example:

string1='aovces'
string2='m o'

so that in the print "I love you guys" in the case, interspersing each element of each string, including the space.

2 answers

3

Just combine the functions zip_longest and chain, both of the module itertools:

from itertools import chain, zip_longest

string1='aovces'
string2='m o'

interpolation = zip_longest(string1, string2, fillvalue='')

print(''.join(chain(*interpolation)))  # amo voces

See working on Ideone | Repl.it

The function zip_longest will return a generator that iterates over a list similar to:

[('a', 'm'), ('o', ' '), ('v', 'o'), ('c', ''), ('e', ''), ('s', '')]

That is, create pairs with a letter of each string and when there are no more characters in one of the strings, fills with the value defined by fillvalue=''. In doing *interpolation as a parameter of chain, all tuples are passed as positional parameters, the equivalent of:

chain(interpolation[0], interpolation[1], interpolation[2], interpolation[3], interpolation[4], interpolation[5])

The function chain, in turn, returns a generator that will iterate over all tuples, one at a time, while there are values. It would be the equivalent of the list:

['a', 'm', 'o', ' ', 'v', 'o', 'c', '', 'e', '', 's', '']

So, in the end, we generate the string with the method join.

This solution will work for any amount of strings, regardless of the size of each.

0

A simple solution:

def entrelacar(string1=None, string2=None):
    s = list(string1)
    s2 = list(string2)
    resp = ''
    while s or s2:
        if s:
            resp += s.pop(0)
        if s2:
            resp += s2.pop(0)
    return resp

if __name__ == '__main__':
    print( entrelacar(string1='aovces', string2='m o'))
  • @Andersoncarloswoss yes, you’re right. I’ve edited the code now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.