2014-09-01 40 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) 
相關問題