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[5] = 'g'
str[6] = 'i'
str[7] = 'r'
str[8] = '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[5] = 'g'
strList[6] = 'i'
strList[7] = 'r'
strList[8] = '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"

    Tweet this to help others

Live Demo

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles