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 = txt.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 = txt.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="T" #use join function to convert list into string txt="".join(lst) print(txt) #This is poopcode