I have a list and string:
fruits = [\'banana\', \'apple\', \'plum\']
mystr = \'i like the following fruits: \'
How can I concatenate them s
The simple code below will work:
print(mystr, fruits)
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
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)
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.
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])