You get Python error, ‘str’ object does not support item assignment, when you try to modify the string which is immutable in nature. Here is the thing, unlike languages like C, you can’t modify the string in Python or Php. But yeah, you can always recreate it.
So, how and where this error appears? Suppose you want to access a character and wish to replace it with another. You can’t do this. What you can do is to change the character using
substring and then again insert it into your variable.
Let’s take an example –
str = 'Superman' // Suppose you want to change // it to Supergirl str = 'g' str = 'i' str = 'r' str = 'l'
This code will throw the error as ‘str’ object does not support item assignment. According to Python glossary –
Immutable is an object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
The correct form of upper code is –
str = 'Superman' // Suppose you want to change // it to Supergirl str = 'Supergirl'
Or, you can also convert the string to list and then alter the characters individually –
str = 'Superman' // Suppose you want to change // it to Supergirl strList = list(str) strList = 'g' strList = 'i' strList = 'r' strList = 'l' str = "".join(strList)
Another way is to slice the string and then join –
str = 'Superman' // Suppose you want to change // it to Supergirl str = str[5:] + "girl"
Demo might not work in private window (incognito)