Fix TypeError: 'str' object does not support item assignment in Python
Python is one of the easiest and most versatile programming languages in the world. Here we are going to figure out one of the most common errors.
The Problem
s1 = "Hello World"
s2 = ""
j = 0
for i in range(len(s1)):
s2[j] = s1[i]
j = j + 1
As shown in the below image, your compiler will throw an runtime error when you run the above code.
The Solution
Let's see how we can solve this problem
Strings in python are immutable, whereas strings in C are mutable. Here is how it can be accomplished:
s1 = "Hello World"
s2 = ""
j = 0
for c in s1:
s2 = s2 + c
print (s2)