Reputation:
I'm trying to write a new string with a for loop but each time the loop goes through an iteration, the string gets rewritten with the new iteration. Is there any way to prevent this?
for i in range(0,len(string1)):
newString = string1[i] + string2[i]
return newString
newString only comes out as the last iteration when I need to newString to be the first iteration to the last.
Upvotes: 0
Views: 45
Reputation: 168636
If you want to accumulate all of per-iteration values, try using the aggregate assignment operator +=
. The following code will return one very long string, which is the concatenation of all of the intermediate strings.
newString = ''
for i in range(0,len(string1)):
newString += string1[i] + string2[i]
return newString
Alternatively, you might want to return a list of the intermediate values, like so:
newList = []
for i in range(0,len(string1)):
newList += [string1[i] + string2[i]]
return newList
Note, however, that it is often a bad idea to append strings in a loop. It causes a lot of memory reallocation. The typical Pythonic form is to collect the intermediate values into a list and ''.join()
them together, like so:
newList = []
for i in range(0,len(string1)):
newList += [string1[i] + string2[i]]
newString = ''.join(newList)
return newString
Equivalently, and more compactly,
return ''.join(''.join(chars) for chars in zip(string1, string2))
Upvotes: 3