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

8

7

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']
Chalkboard answered 13/1, 2018 at 18:29 Comment(3)
output = ["".join([string,str(i)]) for i in List1]Frizzle
@VasilisG. your answer inserts the string into new elements in the list, it's not good. I just want to concatenate the string to the end of the existing elements of the list.Chalkboard
@Chalkboard you have a point there, you can just flip string and str(i) positions in the list.Frizzle
S
8

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']
Shien answered 13/1, 2018 at 18:38 Comment(0)
P
4

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.

Pavid answered 13/1, 2018 at 18:35 Comment(0)
O
1
L = [ 1, 2, 3 ]
s = "a"
print map(lambda x: str(x)+s, L);

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

Obala answered 13/1, 2018 at 18:37 Comment(1)
this is python 2 only, though.Wiegand
P
0

You can use map:

List1 = [ 1 , 2 , 3 ]
string = "a"
new_list = list(map(lambda x:"{}{}".format(x, string), List1))

Output:

['1a', '2a', '3a']
Pinhole answered 13/1, 2018 at 18:35 Comment(0)
S
0
result = map(lambda x:str(x)+'a',List1)
Squinch answered 13/1, 2018 at 18:38 Comment(0)
K
0
List1 = [ 1 , 2 , 3 ]
str1="a"
new_list = []
for item in List1:
    new_list.append(str(item)+str1)
print(new_list)

Convert each element in the list to string and then add the required string to each element of the list.

Kitsch answered 13/1, 2018 at 18:54 Comment(1)
OP wants a one-liner.Wiegand
G
0
>>> List1 = [ 1 , 2 , 3 ]
>>> string = "a"
>>> output = [s + string for s in map(str, List1)]
>>> output
['1a', '2a', '3a']
Galina answered 19/3 at 17:11 Comment(0)
C
-1

A 1 liner:

List1= [s + a for s in List1]
Chalkboard answered 2/2, 2018 at 23:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.