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.
1 2 3 4 5 6 7 |
list_of_strings = ['one', 'two', 'three'] my_string = '' for word in list_of_strings: my_string += str(word) print("Final result:", my_string) |
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.
1 2 3 4 5 6 7 8 9 10 |
list_of_strings = ['one', 'two', 'three'] my_string = '' for word in list_of_strings: my_string += str(word + ",") my_string = my_string[:-1] my_string += '.' print("Final result:", my_string) |
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.
1 |
my_string = my_string[:-1] |
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.
1 |
my_string += '.' |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
list_of_strings = ['one', 'two', 'three'] my_string = '' counter = 0 while counter < list_of_strings.__len__(): my_string += str(list_of_strings[counter] + ",") counter += 1 my_string = my_string[:-1] my_string += '.' print("Final result:", my_string) |
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.
1 |
counter += 1 |
This code returns the same result as before:
Final result: one,two,three.