How can I use str.join() instead of "+=" to join a list of strings with separator?

Question:

I have some code which is essentially this:

data = ["some", "data", "lots", "of", "strings"]
separator = "."

output_string = ""
for datum in data:
    output_string += datum + separator

How can I do this with str.join() or a similar built-in function?

Asked By: Leonora Tindall

||

Answers:

output_string = ".".join(data)

if you have integers or non-strings in data, then

output_string = ".".join( str(x) for x in data )
Answered By: labheshr

If the separator is a variable you can just use variable.join(iterable):

data = ["some", "data", "lots", "of", "strings"]
separator = "."


print(separator.join(data))
some.data.lots.of.strings
Answered By: Padraic Cunningham
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.