22

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Leonora Tindall
  • 1,391
  • 2
  • 12
  • 30

2 Answers2

43

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
6
output_string = ".".join(data)

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

output_string = ".".join( str(x) for x in data )
labheshr
  • 2,858
  • 5
  • 23
  • 34