2014-09-01 42 views
1

简单添加字符串和字符串列表会产生错误cannot concatenate 'str' and 'list' objects。有没有一种更优雅的方式来做到以下几点(例如没有循环)?向列表中的每个单独字符串添加字符串

list_of_strings = ["Hello", "World"] 
string_to_add = "Foo" 

for item, string in enumerate(list_of_strings): 
    list_of_strings[item] = string_to_add + string 

# list_of_strings is now ["FooHello", "FooWorld"] 
+2

话虽这么说,你的解决方案可能是最有效的,因为它并不需要创建一个中间表。 – 2014-09-01 12:14:42

回答

6

使用理解:

list_of_strings = [s + string_to_add for s in list_of_strings] 
2

尝试使用地图

list_of_strings = ["Hello", "World"] 
string_to_add = "Foo" 


print map(lambda x:string_to_add+x,list_of_strings) 
相关问题