How to concatenate strings in different lists

Thomas Nyberg tomuxiong at gmx.com
Wed Nov 23 13:03:14 EST 2016


On 11/23/2016 12:40 PM, Daiyue Weng wrote:
> Hi, I am wondering how to concatenate corresponding strings in two lists,
> assuming that the lists are of same length, e.g.
>
> val_1 = ['a', 'b', 'c']
> val_2 = ['A', 'B', 'C']
>
> # concatenate corresponding strings in 'val_1' and 'val_2'
> # and put results in another list 'val' so that
> # val = ['aA', 'bB', 'cC']
>
> cheers
>
Hello,

The easiest is probably first to zip them (i.e. pair the corresponding 
pieces together) and then to join them as you normally would with lists 
of strings:

 >>> print([''.join(pair) for pair in zip(val_1, val_2)])
['aA', 'bB', 'cC']

That uses list comprehensions which might be a bit confusing. In two 
steps, you could do the following

 >>> pairs = zip(val_1, val_2)
 >>> catted_strings = []
 >>> for pair in pairs:
         catted_string = ''.join(pair)
         catted_strings.append(catted_string)
 >>> print(catted_strings)
['aA', 'bB', 'cC']

Hope this this helps.

Cheers,
Thomas



More information about the Python-list mailing list