Search code examples
pythonstringlistconcatenation

How to concatenate (join) items in a list to a single string


How do I concatenate a list of strings into a single string?

For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?


For handling a few strings in separate variables, see How do I append one string to another in Python?.

For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.


Solution

  • Use str.join:

    >>> words = ['this', 'is', 'a', 'sentence']
    >>> '-'.join(words)
    'this-is-a-sentence'
    >>> ' '.join(words)
    'this is a sentence'