Foad S. Farimani
Foad S. Farimani

Reputation: 14008

Interleave two multiline strings in Python

I want to do exactly what has been in this post, except in Python. Consider two strings:

s1='AAA1
    AAA2
    AAA3'
s2='BBB1
    BBB2
    BBB3'

I want to have combine(s1,s2) to return:

s3='AAA1BBB1
    AAA2BBB2
    AAA3BBB3'

You may consider that these strings are actually very long and I want this processes to be performant. I would appreciate if you could help me know how to do this.

Upvotes: 2

Views: 179

Answers (3)

timgeb
timgeb

Reputation: 78670

Multiline-strings are denoted with ''' in Python.

>>> s1 = '''AAA1
...:AAA2
...:AAA3'''
>>> 
>>> s2 = '''BBB1
...:BBB2
...:BBB3'''

You can split them with str.splitlines and interleave them with zip.

>>> strings = [s1, s2]
>>> pairs = zip(*(s.splitlines() for s in strings))
>>> result = '\n'.join(''.join(pair) for pair in pairs)
>>> 
>>> print(result)
AAA1BBB1
AAA2BBB2
AAA3BBB3

A generic function that accepts any number of multiline strings using the *args syntax can be written as follows.

>>> def combine(*strings):
...:    lines = zip(*(s.splitlines() for s in strings))
...:    return '\n'.join(''.join(line) for line in lines)
>>> 
>>> str1 = '''A
...:D
...:H'''
>>> str2 = '''B
...:E
...:I'''
>>> str3 = '''C
...:F
...:J'''
>>> 
>>> print(combine(str1, str2, str3))
ABC
DEF
HIJ

Note that zip truncates the iterable it produces to the length of its shortest argument, i.e. the result has as many lines as the shortest multiline string passed to combine.

If you expect strings with different numbers of lines and need fill-values, you can play around with zip_longest from the itertools module.

Upvotes: 3

mad_
mad_

Reputation: 8273

Use splitlines() and then zip two list together

s1="AAA1\nAAA2\nAAA3"
s2="BBB1\nBBB2\nBBB3"

l1 = s1.splitlines()
l2 = s2.splitlines()

print('\n'.join([i+j for i,j in zip(l1,l2)]))

Output

AAA1BBB1
AAA2BBB2
AAA3BBB3

Upvotes: 1

clearshot66
clearshot66

Reputation: 2302

This may work for what you're looking to get if there's newlines involved:

s1="AAA1\nAAA2\nAAA3"
s2="BBB1\nBBB2\nBBB3"

ms1 = s1.splitlines()
ms2 = s2.splitlines()

new_list = []

i = 0
while i < 3:
  new_list.append( ms1[i]+ms2[i] )
  i = i + 1

print(new_list)

Upvotes: 1

Related Questions