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
Answer
Use join
:
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
No comments:
Post a Comment