TypeError: ‘str’ object does not support item assignment

TypeError: ‘str’ object does not support item assignment error occurs when we tried to change or replace characters of a string. In Python, the strings are immutable which means they cannot be changed once created. The simplest solution to the error is to make change the characters of the string into a list and then replace the elements of the list. After replacing, we can again join the list items together to make a string. In this short article, we will learn how we can solve TypeError: ‘str’ object does not support item assignment errors using various possible ways. Moreover, we will discuss various methods to replace characters in a string.

TypeError: 'str' object does not support item assignment-error

TypeError: ‘str’ object does not support item assignment – Possible Solutions

TypeError: ‘str’ object does not support item assignment is a common type of error when dealing with strings. Strings are simply arrays of bytes representing Unicode characters. In Python, the strings are immutable which means once they are created, they cannot be changed. And when we tried to change the characters of the string, we get TypeError: ‘str’ object does not support item assignment error which means string in Python does not support the assignment. There can be many possibilities to solve this error. One of the possible ways to get rid of TypeError: ‘str’ object does not support item assignment error is to convert the string into a list and then changed the elements.

# creating a string
string = "My name is bAshir"

# changing element or accessing element
string[0]= 'm'

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_32759/638850905.py in <module>
      3 
      4 # changing element or accessing element
----> 5 string[0]= 'm'

TypeError: 'str' object does not support item assignment

As you can see, we got the error because the individual characters of the string object cannot be accessed and changed in Python.

Solution-1: changing string into a list

As we discussed, one of the possible ways to get rid of the TypeError: ‘str’ object does not support item assignment error is to use lists.

  1. Change the string into a list
  2. Update the list by adding or removing the elements
  3. Conver the list items back into a string
  4. We will have an updated string
# creating a string
string = 'ny name is bashir'

# converting string into list
my_list = list(string)

# printing the list
print(my_list)

Output:

['n', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'b', 'a', 's', 'h', 'i', 'r']

Notice that each of the characters in the string is separated into individual elements in the list. Now we can use indexing to access and change the elements of the list.

The indexing in Python starts from 0, so to access the first element, we will use zero as an index value.

Let us change the first element of the list and then join the elements again together to create a string:

# changing the element
my_list[0]='M'

# creating new string
new_str = ''.join(my_list)

# printing the string
print(new_str) 

Output:

My name is bashir

Notice that we have changed the first character of the string successfully.

Solution-2: Using string slicing in Python

Slicing of strings is to get access to substrings from the main string. Let us assume that we have a string “Bashir Alam”, then we can access the first name using the slicing method.

Let us assume that we have the following string and we want to replace the “%” symbol with a white space.

# string
string ="Bashir%Alam"

We can use the slicing method to access the first and last names and put white space in between them.

First, let us find the index position of the symbol % using the index() method:

# string define
string="Bashir%Alam"

# finding the index value
index_value = string.index('%')

# printing the index value
print(index_value)

Output:

6

Notice that the position of the % symbol is 6. So, we can get the first string from 0 to 6 and then the second string from 7 to the end and join both of them using space.

# string define
string="Bashir%Alam"

# finding the index value
index_value = string.index('%')

# new string with a space
new_str = string[0:index_value] + ' ' + string[index_value+1:]

# printing the string
print(new_str)

Output:

Bashir Alam

Note that we have replaced the % symbol with a space.

Solution-3: Using replace() method

Another way to change the characters of the string without getting TypeError: ‘str’ object does not support item assignment error is to use replace() method. The replace method returns the copy of the string which is replaced by the specified character:

The replace method takes two required parameters with one optional parameter:

  1. The substring that you want to replace
  2. The substring you want to insert

Let us assume that we have a string and we want to replace the % symbol with a space:

# creating a string
string = 'Bashir%Alam'

# replacing the character
new_str = string.replace('%', ' ')

# printing
print(new_str)

Output:

Bashir Alam

Notice that we have replaced the % symbol with a space without getting TypeError: ‘str’ object does not support item assignment error.

If you have multiple occurrences of the % symbol but you only want to replace the first one, you can specify the optional parameter value in replace() method as shown below:

# creating a string
string = '%Bashir%Alam%'

# replacing the character
new_str = string.replace('%', ' ', 1)

# printing
print(new_str)

Output:

Bashir%Alam%

Notice that we have replaced the % symbol in one place only.

Solution-4: Using for loop

Another method to get rid of the TypeError: ‘str’ object does not support item assignment error is to use for loop. We will iterate through the string using for loop and can replace any special character with a space.

# defining string
string = "Bashir23Alam"

string2 =''
# using for loop to iterate
for c in range(len(string)):
    if not string[c].isnumeric():
        string2 += string[c]

print(string2)

Output:

BashirAlam

Note that we have changed the numeric values from the string using for loop:

Understanding TypeError: ‘str’ object does not support item assignment error

In Python usually, the errors give much more information and can be easily solved. The errors have two main parts. The first part of the error represents the category of the error which in this case is the TypeError. The second part of the error gives more specific details about the error. In this case, it says that the string object does not support the assignment of the item. This means we are trying to change the elements or assign new character values to the string which is not directly allowed in Python:

What is Type Error in Python?

A TypeError in Python is simply when we apply an operation on an object which is not allowed. For example, strings are immutable and when we tried to change the character of strings, we will get TypeError.

What is a string in Python?

A String is simply an array that contains characters. Anything which is inside the quotation marks in Python is considered to be a string. Strings are immutable which means once they are created they cannot be changed.

For example, the following are examples of strings in Python:

# string with single quotation marks
a = 'This is string'

# string with double quotation marks
b = "This is string"

Summary

In this short article, we discussed how we can solve TypeError: ‘str’ object does not support item assignment error. We covered four different methods through which we can get rid of TypeError: ‘str’ object does not support item assignment error. Moreover, we also discussed how to understand errors in Python so that in the future we can easily understand and solve them.

Related Issues:

Leave a Comment

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

Scroll to Top