5
votes

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? (or is it not possible?)

2
output_string = ".".join(data) - MattDMo
The title is confusing. How is this different from how str.join is normally used? - wflynny
I don't see "multiple iterables interleaving" here - Chad S.
Yep, I was confused about str.join(). Sorry. - Leonora Tindall

2 Answers

16
votes

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
0
votes
output_string = ".".join(data)

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

output_string = ".".join( str(x) for x in data )