Fred S
Fred S

Reputation: 1511

Add a string to each individual string in a list

Simple addition of a string and a list of strings yields the error cannot concatenate 'str' and 'list' objects. Is there a more elegant way to do the following (e.g. without the loop)?

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

Upvotes: 1

Views: 88

Answers (2)

sundar nataraj
sundar nataraj

Reputation: 8692

try using map

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


print map(lambda x:string_to_add+x,list_of_strings)

Upvotes: 2

Jayanth Koushik
Jayanth Koushik

Reputation: 9874

Use comprehension:

list_of_strings = [s + string_to_add for s in list_of_strings]

Upvotes: 6

Related Questions