‘str’ object does not support item assignment

In Python, strings are immutable, so you can’t change their characters in-place.

You can, however, do the following:

for c in s1:
    s2 += c

The reasons this works is that it’s a shortcut for:

for c in s1:
    s2 = s2 + c

The above creates a new string with each iteration, and stores the reference to that new string in s2.

Leave a Comment

tech