Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
Answer from Burhan Khalid on Stack OverflowUse str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
How do I concatenate two lists in Python?
python - How to concatenate a string and a list? - Stack Overflow
Function to join list items into string with delimiter
Python concat string with list - Stack Overflow
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 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
How would I turn the following code into a function? The goal is to take a list of colors and return a string with "+" in between each color from the list. The code below returns: the best colors are : blue + yellow.
I'm looking to create a function colors(): in which I could pass any list of colors instead of hardcoding it below. For example, colors(['green', 'red', 'black']) would return: the best colors are : green + red + black
input_list = ['blue', 'yellow']
delim = " + "
res = delim.join([str(ele) for ele in input_list])
print('the best colors are' + ' : ' + str(res))