how to concatenate two formatted strings in python

262 Views Asked by At

Is there a way to concatenate these two formatted strings horizontally? I tried a + b but am having a vertically concatenated strings.

here is a screen shot of the formatted strings.

a =  '''
      __  
     (  ) 
      )(  
     (__) 
   '''
b = '''
    ____ 
   (  __)
    ) _) 
   (__) 
  '''
 print(a+b) #I don't need this I need horizontal way of concatenation
3

There are 3 best solutions below

2
On BEST ANSWER

You can do something similar to this

>>> lines = zip(a.split('\n'), b.split('\n'))
>>> ab = '\n'.join([ai + bi for ai, bi in lines])
>>> print ab

      __      ____ 
     (  )    (  __)
      )(      ) _) 
     (__)    (__) 

>>> 
1
On

You can concatenate line by line as follows.

c = [x + y for x, y in zip(a.split('\n'), b.split('\n'))] 
# x + y is line by line concatenation
# zip is selecting a pair of lines at a time from a & b

print('\n'.join(c))

Output

  __      ____ 
 (  )    (  __)
  )(      ) _) 
 (__)    (__) 
0
On

A straight answer could be simple if we define the two formatted strings using 'arrays'. The answer is:

aa = ["___"],["()"],[")("]
bb = ["___"],[")("],["()"]
print (aa)
print (bb)

cc=[]
for index in range(3):
   cc.append(aa[index]+ bb[index])

print (cc[0][0], cc[0][1])
print (cc[1][0], cc[1][1])
print (cc[2][0], cc[2][1])

The formatted strings are different from the example but we hope that the concept is clear.

Result:

enter image description here