-1

I'm using Python 3.7. I want to turn a list of elements into a string by concatenating each element and inserting a string in between them. So if my list consists of

"a", "b", "c"

I would like the result to be

"a-b-c"

I can't find a single Python function to do this. Does one exist? I have resorted to writing this

def concatenate_list_data(list):
    result= ''
    for element in list:
        result += "-"
        result += element
    return result

but figure there is a more elegant way to do it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Dave
  • 15,639
  • 133
  • 442
  • 830
  • 1
    Does this answer your question? [Concatenate item in list to strings](https://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings) – Brian61354270 Apr 01 '20 at 21:23

2 Answers2

1

You could use join:

result = '-'.join(mylist)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

join is exactly for you:

res = '-'.join(my_list) where my_list is your iterable.

Gabio
  • 9,126
  • 3
  • 12
  • 32