How to concatenate items in a list to a single string?

alvas picture alvas · Sep 17, 2012 · Viewed 1.3M times · Source

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str


Burhan Khalid picture Burhan Khalid · Sep 17, 2012

Use join:

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