Search code examples
pythonstringlistconcatenationstring-concatenation

Concatenate string to the end of all elements of a list in python


I would like to know how to concatenate a string to the end of all elements in a list.

For example:

List1 = [ 1 , 2 , 3 ]
string = "a"

output = ['1a' , '2a' , '3a']

Solution

  • rebuild the list in a list comprehension and use str.format on both parameters

    >>> string="a"
    >>> List1 = [ 1 , 2 , 3 ]
    >>> output = ["{}{}".format(i,string) for i in List1]
    >>> output
    ['1a', '2a', '3a']