23
votes

I have a list and string:

fruits = ['banana', 'apple', 'plum']
mystr = 'i like the following fruits: '

How can I concatenate them so I get (keeping in mind that the enum may change size) 'i like the following fruits: banana, apple, plum'

5

5 Answers

25
votes

Join the list, then add the strings.

print mystr + ', '.join(fruits)

And don't use the name of a built-in type (str) as a variable name.

8
votes

You can use this code,

fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry']
mystr = 'i like the following fruits: '
print (mystr + ', '.join(fruits))

The above code will return the output as below:

i like the following fruits: banana, apple, plum, pineapple, cherry
4
votes

You can use str.join.

result = "i like the following fruits: "+', '.join(fruits)

(assuming fruits only contains strings). If fruits contains a non-string, you can convert it easily by creating a generator expression on the fly:

', '.join(str(f) for f in fruits)
1
votes

You're going to have a problem if you name your variables the same as Python built-ins. Otherwise this would work:

s = s + ', '.join([str(fruit) for fruit in fruits])
0
votes

The simple code below will work:

print(mystr, fruits)