26

I have a list and a string:

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

How can I concatenate them so I get

'i like the following fruits: banana, apple, plum'

Keep in mind that the enum may change size.

5 Answers 5

28

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.

Sign up to request clarification or add additional context in comments.

Comments

12

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

Comments

6

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)

Comments

1

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

Comments

0

The simple code below will work:

print(mystr, fruits)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.