Skip to content

TypeError: ‘str’ object does not support item assignment – Python error – How to fix?

Python strings are immutable and they cannot be changed during the course of Python program execution.

In Python, strings cannot be modified. You need to create a new string based on the contents of an old one if you want to change a string.

The ‘str’ object does not support item assignment” error tells you that you are trying to modify the value of an existing string.

txt = "this is poopcode"
#trying to assign uppercase version
txt[0] = txt[0].upper()
TypeError: 'str' object does not support item assignment.

The solution is to create a new string from the existing string and assign it to the variable.

In this case, we can use the in-built Python function capitalize() to create uppercase version of the string and assign to the variable

txt = "this is poopcode"
#trying to assign uppercase version
txt[0] = txt[0].capitalize()

But in general this error can be fixed by convert this string into a list first and then updating its value.

txt = "this is poopcode"

lst=list(txt)

lst[0]="T"

#use join function to convert list into string
txt="".join(lst)

print(txt)

#This is poopcode
See also  How to Format Dates in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.