简体   繁体   中英

how to concatenate two formatted strings in python

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

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

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

>>> 

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

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

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM