In Python, strings are immutable, so we will get the
str object does not support item assignment error when trying to change the string.
You can not make some changes in the current value of the string. You can either rewrite it completely or convert it into a list first.
This whole guide is all about solving this error. Let’s dive in.
str object does not support item assignment Error in Python
As the strings are immutable, we can not assign a new value to one of its indexes. Take a look at the following code.
#String Variable string="Hello Python" #printing Fourth index element of the String print(string) #Trying to Assign value to String string="a"
The above code will give
o as output, and later it will give an error once a new value is assigned to its fourth index.
The string works as a single value; although it has indexes, you can not change their value separately. However, if we convert this string into a list first, we can update its value.
#String Variable string="Hello Python" #printing Fourth index element of the String print(string) #Creating list of String elements lst=list(string) print(lst) #Assigning value to the list lst="a" print(lst) #use join function to convert list into string new_String="".join(lst) print(new_String)
o ['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n'] ['H', 'e', 'l', 'l', 'a', ' ', 'P', 'y', 't', 'h', 'o', 'n'] Hella Python
The above code will run perfectly.
First, we create a list of string elements. As in the list, all elements are identified by their indexes and are mutable.
We can assign a new value to any of the indexes of the list. Later, we can use the join function to convert the same list into a string and store its value into another string.