In Python, strings are immutable, which means we cannot change certain characters or the text of a string using the assignment operator. If you try to change the string value, the Python interpreter will raise TypeError: ‘str’ object does not support item assignment.
In this tutorial, we will look at what exactly TypeError: ‘str’ object does not support item assignment means and how we can resolve this error with examples.
What is TypeError: ‘str’ object does not support item assignment?
Let us take a simple example to demonstrate this issue.
In the following code, we are accepting a username as an input parameter. If the username consists of non-alphanumeric characters, we are trying to replace those characters in a string with an empty character.
When we run the code, we will get str object does not support item assignment error.
username = input("Enter a username: ")
for i in range(len(username)):
if not username[i].isalnum():
username[i] = ""
print(username)
Output
Enter a username: ^*P&YTHON
Traceback (most recent call last):
File "c:\Personal\IJS\Code\prgm.py", line 4, in <module>
username[i] = ""
TypeError: 'str' object does not support item assignment
We get the TypeError because we tried to modify the string value using an assignment operator. Since strings are immutable, we cannot replace the value or certain characters of a string using its index and assignment operator.
How to resolve TypeError: ‘str’ object does not support item assignment?
Since strings are mutable, we need to create a newly updated string to get the desired result.
Let us take an example of how a memory allocation happens when we update the string with a new one.
text1 = "ItsMyCode"
text2 = text1
print("Memory Allocation ", id(text1))
print("Memory Allocation ", id(text2))
text1 = "ItsMyCode Python"
print("Memory Allocation ", id(text1))
print("Memory Allocation ", id(text2))
Output
Memory Allocation 1999888980400
Memory Allocation 1999888980400
Memory Allocation 1999889178480
Memory Allocation 1999888980400
In the above code, notice that when we change the content of the text1 with an updated string, the memory allocation too got updated with a new value; however, the text2 still points to the old memory location.
We can solve this issue in multiple ways. Let us look at a few better solutions to handle the scenarios if we need to update the string characters.
Solution 1 – Creating a new string by iterating the old string
The simplest way to resolve the issue in the demonstration is by creating a new string.
We have a new string called username_modified
, which is set to empty initially.
Next, using the for loop, we iterate each character of the string, check if the character is a non-alphanumeric value, and append the character to a new string variable we created.
username = input("Enter a username: ")
username_modified = ""
for i in range(len(username)):
if username[i].isalnum():
username_modified += username[i]
print(username_modified)
Output
Enter a username: ^*P&YTHON
PYTHON
Solution 2- Creating a new string using a list
Another way is to split the string characters into a list, and using the index value of a list; we can change the value of the characters and join them back to a new string.
text = "ItsMyCode Cython Tutorial"
# Creating list of String elements
lst = list(text)
print(lst)
# Replace the required characters in the list
lst[10] = "P"
print(lst)
# Use join() method to concatenate the characters into a string.
updated_text = "".join(lst)
print(updated_text)
Output
['I', 't', 's', 'M', 'y', 'C', 'o', 'd', 'e', ' ', 'C', 'y', 't', 'h', 'o', 'n', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l']
['I', 't', 's', 'M', 'y', 'C', 'o', 'd', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l']
ItsMyCode Python Tutorial
Conclusion
The TypeError: ‘str’ object does not support item assignment error occurs when we try to change the contents of the string using an assignment operator.
We can resolve this error by creating a new string based on the contents of the old string. We can also convert the string to a list, update the specific characters we need, and join them back into a string.