HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howstringsinglelistjoinitemsconcatenate

Problem

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'

Code Snippets

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

Context

Stack Overflow Q#12453580, score: 2095

Revisions (0)

No revisions yet.