Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 759
Markus84612 Avatar asked Jan 13 '18 18:01

Markus84612


2 Answers

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']
like image 91
Jean-François Fabre Avatar answered Nov 15 '22 10:11

Jean-François Fabre


In one line:

>>> lst = [1 , 2 , 3]
>>> my_string = 'a'
>>> [str(x) + my_string for x in lst]
['1a', '2a', '3a']

You need to convert the integer into strings and create a new strings for each element. A list comprehension works well for this.

like image 20
Mike Müller Avatar answered Nov 15 '22 10:11

Mike Müller