Online Tutorials & Training Materials | STechies.com
Register Login

TypeError 'str' object does not support item assignment

11 Feb 2020 6:09 am || 0

TypeError 'str' object does not support item assignment

While working with strings in Python, you might have come across the error typeerror 'str' object does not support item assignment.  This error usually occurs when you are changing an immutable object such as a string. If you try to alter the characters of a string or assign other characters in their positions, this error will be raised. This is because strings in Python are immutable, and cannot be modified after creation.

We will focus on the details of this error and also look at the possible solutions.

Example

Suppose there is a string Str=”Python”. If you try to change the first letter like this:

#Intialising the string variable str1
str1="Stechies"

#Assigning new value at index 0
str1[0]="Python"

print(str1)

This will throw the TypeError:

'str' object does not support item assignment

TypeError 'str' object does not support item assignment

Correct Code:

#Intialising the string variable str1
str1 = 'Stechies'

print('Memory address for String str1: ',id(str1)) #Output: 28675192

str1= 'Python'

print('Memory address for String str1: ',id(str1)) #Output: 20719552

Output:

Memory address for String str1: 28675192
Memory address for String str1: 20719552

This will work like a charm as you are not trying to change the string itself. Instead, you are changing a reference to the string, which is "str1" in this case.

In the above example, if we print the memory address of the string ‘str1’ after assigning 2 different values we get 2 different memory locations.

In python, the memory address is assigned to the value of the variable and not the variable itself. So in this, case 'str1' has two different memory addresses since it holds two different values.