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

拈花ヽ惹草 提交于 2021-01-27 14:23:45

问题


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']

回答1:


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']



回答2:


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.




回答3:


L = [ 1, 2, 3 ]
s = "a"
print map(lambda x: str(x)+s, L);

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




回答4:


You can use map:

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

Output:

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



回答5:


result = map(lambda x:str(x)+'a',List1)



回答6:


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.




回答7:


A 1 liner:

List1= [s + a for s in List1]


来源:https://stackoverflow.com/questions/48243018/concatenate-string-to-the-end-of-all-elements-of-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!