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)

Further Reading

  1. Why map entries are unddressable in Golang?
  2. [SOLVED] psql: FATAL database 'root' does not exist error
  3. What is Atatus APM and its Benefits?

Monitor your software stack for free with Atatus.

Start your free trial
Request a Demo

Free 14-day trial. No credit card required. Cancel anytime.

Ready to see actionable data?

Avail Atatus features for 14 days free-trial. No credit card required. Instant set-up.