String concatenation '+=' in loop
时间: 2024-01-20 22:03:00 浏览: 138
The string concatenation operator '+=' is used to append new string values to an existing string variable in a loop. For example, let's say you have a loop that iterates through a list of words and you want to concatenate them into a single string separated by a space. You can do it like this:
```
words = ["hello", "world", "how", "are", "you"]
result = ""
for word in words:
result += word + " "
print(result)
```
In this example, the loop iterates through each word in the `words` list, and the `+=` operator appends each word to the `result` variable with a space. Finally, the `result` variable is printed, which outputs:
```
hello world how are you
```
Note that the `+=` operator creates a new string object every time it is used, so it is not very efficient for large string concatenations. In those cases, it is better to use the `join()` method which is optimized for concatenating large strings.
阅读全文