I have a list with some text:
my_list = ['sentence1','sentence2','sentence3','sentence4' ]
And I want as output a string like this:
'sentence1, sentence2, sentence3, sentence4'
If I make this, I get an aditional ', '
at the end
string_sentences = ''
for sentence in my_list:
string_sentences += sentence +', '
string_sentences
output: 'sentence1, sentence2, sentence3, sentence4, '
same with this approach, but now at the beginning:
string_sentences = ''
for sentence in my_list:
string_sentences += ', ' + sentence
string_sentences
', sentence1, sentence2, sentence3, sentence4'
Only thing I can think to solve it is to keep track of the indices
string_sentences = ''
for i,sentence in enumerate(my_list):
if i +1 < len(my_list):
string_sentences += sentence +', '
else:
string_sentences += sentence
string_sentences
ouput: 'sentence1, sentence2, sentence3, sentence4'
But this seems like a very common issues, and I wonder whether is a more pythonic way to solve it.