Append String in a Loop in Python

If you have a list of strings and you want to concatenate them to create a single string made of these elements, you can use the For loop.

With each pass of the loop, the next word is added to the end of the string. The result is a single word.

Final result: onetwothree

The problem with this approach is that there are no separators between characters. We can easily fix that inside the loop. We are going to separate words with a comma.

Now, with each pass, there is a word and comma added to the end of the string.

Before printing the result, we have to remove the comma at the end of the string, that was added in the last pass.

This code assigns the my_string variable without the last character (which is a comma) to itself.

At the end of the string, we are going to add a dot.

If you run this code, you are going to get this result.

Final result: one,two,three.

The While Loop

If you prefer to use the While loop, you need to create a counting variable and know how many words are there inside the list.

This loop continues to meet the requirement when the counter variable is lower than the number of words inside the list. Each time the counter variable is incremented.

This code returns the same result as before:

Final result: one,two,three.