Python TypeError: ‘str’ object does not support item assignment Solution

By | October 24, 2021
Python TypeError 'str' object does not support item assignment Solution

A Python string is a sequence of characters. The string characters are immutable, which means once we have initialized a string with a sequence of characters, we can not change those characters again. This is because the string is an immutable data type.

Similar to the Python list, the Python string also supports indexing, and we can use the index number of an individual character to access that character. But if we try to change the string’s character value using indexing we would receive the TypeError: 'str' object does not support item assignment Error.

This guide discusses the following string error and its solution in detail. It also demonstrates a common example scenario, so you can solve the following error for yourself.

Let’s get started with the error statement.

Python Problem: TypeError: ‘str’ object does not support item assignment

The Error TypeError: 'str' object does not support item assignment occur in a Python program when we try to change any character of an initialized string.

Error example

#string
message = "this is a string"

#try to change the first chracter
message [0] = "T"

print(message )

Output

Vamware
Traceback (most recent call last):
  File "main.py", line 5, in 
    string[0] = "T"
TypeError: 'str' object does not support item assignment

The following error statement has two sub statements separated with colon : specifying what is wrong with the program.

  1. TypeError (Exception Type)
  2. ‘str’ object does not support item assignment

1. TypeError

TypeError is a standard Python exception raised by the Python when we perform an invalid operation on an unsupported Python data type.

In the above example, we are receiving this Exception because we tried to assign a new value to the first character of the string “message“. And string characters do not support reassigning, that’s why Python raised the TypeError exception.

2.  ‘str’ object does not support item assignment

'str' object does not support item assignment statement is the error message, telling us that we are trying to assign a new character value to the string. And string does not support item assignment.

Solution

In the above example, we were trying to change the first character of the string message. And for that, we used the assignment operator on the first character message[0]. And because of the immutable nature of the string, we received the error.

There are many ways to solve the above problem, the easiest way is by converting the string into a list using the list() function. Change the first character and change list back to the string using the join() method.

#string
string = "this is a string"

#convert the string to list
string = list(string)

#change the first character
string[0] ="T"

#change back the list into string using join() method
string = "".join(string)

print(string)

Output

This is a string

Common Example Scenario

Now let’s discuss an example scenario where many Python learners commit a mistake in the program and encounter this error.

Error Example

Suppose, we need to write a program that accepts a username from the user. And we need to filter that username by removing all the numbers and special characters. The end username should contain only the upper or lowercase alphabets characters.

#input the username
username = input("Enter your username(do not use any number and special character):  ")

#filter the username
for index in range(len(username)):
    #check if the chracter is not an alphabet
    if not username[index].isalpha():
        #replace that chracter with ""
        username[index] = ""     #error

print(username)

Output

Enter your username(do not use any number and special character):  Admin123@
Traceback (most recent call last):
  File "main.py", line 9, in 
    username[index] = ""
TypeError: 'str' object does not support item assignment

Error Reason

In the above example, we are getting this error because in line 9 we are trying to change the content of the string username using the assignment operator username[index] = "".

Solution

We can use different techniques to solve the above problems and implement the logic. We can convert the username string to a list, filter the list, and then convert it into the string.

#input the username
username = input("Enter your username(do not use any number and special character): ")

#convert the username to list
username = list(username)

#filter the username
for index in range(len(username)):
    #check if the chracter is not an alphabet
    if not username[index].isalpha():
        #replace that chracter with ""
        username[index] = ""     #error

#convert the username list to string
username = "".join(username)

print(username)

Output

Enter your username(do not use any number and special character): admin@123
admin

Now our code run successfully, and it also converted our entered admin@123 username to a valid username admin.

Conclusion

In this Python tutorial, we learned what is “TypeError: ‘str’ object does not support item assignment” Error in Python and how to debug it. Python raises this error when we accidentally try to assign a new character to the string value. Python string is an immutable data structure and it does not support item assignment operation. If you are getting a similar error in your program, please check your code and try another way to assign the new item or character to the string.

If you are stuck in the following error, you can share your code and query in the comment section. We will try to help you in debugging.

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *