Skip to main content

6.4) Joining Strings From A List


Now that you know about lists and strings, we can introduce a method to join up a list of strings into a single string. We will be using a string method rather than a list method.

>>> ' '.join(['This','is','a','sentence'])
'This is a sentence’
>>> shopping_list = ', '.join(['apples','oranges','bananas','coconut'])
>>> shopping_list
'apples, oranges, bananas, coconut'

The join() method operates on a string (its object); in the first example the string is ' ' (a space) and in the second it is ', ' (a comma and space).  The string is then used to join a list of strings, which is given as the argument (i.e. in parentheses) - in this case the list ['apples','oranges','bananas','coconut']. This may not seem intuitive (it feels like it should be the other way around), but it is actually very flexible.