How to Solve Python TypeError: ‘str’ object does not support item assignment

by | Programming, Python, Tips

Strings are immutable objects, which means you cannot change them once created. If you try to change a string in place using the indexing operator [], you will raise the TypeError: ‘str’ object does not support item assignment.

To solve this error, you can use += to add characters to a string.

a += b is the same as a = a + b

Generally, you should check if there are any string methods that can create a modified copy of the string for your needs.

This tutorial will go through how to solve this error and solve it with the help of code examples.


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

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.

The part 'str' object tells us that the error concerns an illegal operation for strings.

The part does not support item assignment tells us that item assignment is the illegal operation we are attempting.

Strings are immutable objects which means we cannot change them once created. We have to create a new string object and add the elements we want to that new object. Item assignment changes an object in place, which is only suitable for mutable objects like lists. Item assignment is suitable for lists because they are mutable.

Let’s look at an example of assigning items to a list. We will iterate over a list and check if each item is even. If the number is even, we will assign the square of that number in place at that index position.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for n in range(len(numbers)):
    if numbers[n] % 2 == 0:
        numbers[n] = numbers[n] ** 2
print(numbers)

Let’s run the code to see the result:

[1, 4, 3, 16, 5, 36, 7, 64, 9, 100]

We can successfully do item assignment on a list.

Let’s see what happens when we try to change a string using item assignment:

string = "Research"
string[-1] = "H"
print(string)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e8e5f13bba7f> in <module>
      1 string = "Research"
----> 2 string[-1] = "H"
      3 print(string)

TypeError: 'str' object does not support item assignment

We cannot change the character at position -1 (last character) because strings are immutable. We need to create a modified copy of a string, for example using replace():

string = "Research"
new_string = string.replace("h", "H")
print(new_string)

In the above code, we create a copy of the string using = and call the replace function to replace the lower case h with an upper case H.

ResearcH

Let’s look at another example.

Example

In this example, we will write a program that takes a string input from the user, checks if there are vowels in the string, and removes them if present. First, let’s define the vowel remover function.

def vowel_remover(string):

    vowels = ["a", "e", "i" , "o", "u"] 

    for ch in range(len(string)):

        if string[ch] in vowels:

            string[ch] = ""

    return string

We check if each character in a provided string is a member of the vowels list in the above code. If the character is a vowel, we attempt to replace that character with an empty string. Next, we will use the input() method to get the input string from the user.

string = input("Enter a string: ")

Altogether, the program looks like this:

def vowel_remover(string):

    vowels = ["a", "e", "i", "o", "u"] 

    for ch in range(len(string)):

        if string[ch] in vowels:

            string[ch] = ""

    return string

string = input("Enter a string: ")

new_string = vowel_remover(string)

print(f'String with all vowels removed: {new_string}')

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-7bd0a563e08b> in <module>
      8 string = input("Enter a string: ")
      9 
---> 10 new_string = vowel_remover(string)
     11 
     12 print(f'String with all vowels removed: {new_string}')

<ipython-input-6-7bd0a563e08b> in vowel_remover(string)
      3     for ch in range(len(string)):
      4         if string[ch] in vowels:
----> 5             string[ch] = ""
      6     return string
      7 

TypeError: 'str' object does not support item assignment

The error occurs because of the line: string[ch] = "". We cannot change a string in place because strings are immutable.

Solution #1: Create New String Using += Operator

We can solve this error by creating a modified copy of the string using the += operator. We have to change the logic of our if statement to the condition not in vowels. Let’s look at the revised code:

def vowel_remover(string):

    new_string = ""

    vowels = ["a", "e", "i", "o", "u"] 

    for ch in range(len(string)):

        if string[ch] not in vowels:

            new_string += string[ch]

    return new_string

string = input("Enter a string: ")

new_string = vowel_remover(string)

print(f'String with all vowels removed: {new_string}')

Note that in the vowel_remover function, we define a separate variable called new_string, which is initially empty. If the for loop finds a character that is not a vowel, we add that character to the end of the new_string string using +=. We check if the character is not a vowel with the if statement: if string[ch] not in vowels.

Let’s run the code to see the result:

Enter a string: research
String with all vowels removed: rsrch

We successfully removed all vowels from the string.

Solution #2: Create New String Using str.join() and list comprehension

We can solve this error by creating a modified copy of the string using list comprehension. List comprehension provides a shorter syntax for creating a new list based on the values of an existing list.

Let’s look at the revised code:

def vowel_remover(string):

    vowels = ["a", "e", "i", "o", "u"] 

    result = ''.join([string[i] for i in range(len(string)) if string[i] not in vowels])

    return result

string = input("Enter a string: ")

new_string = vowel_remover(string)

print(f'String with all vowels removed: {new_string}')

In the above code, the list comprehension creates a new list of characters from the string if the characters are not in the list of vowels. We then use the join() method to convert the list to a string. Let’s run the code to get the result:

Enter a string: research
String with all vowels removed: rsrch

We successfully removed all vowels from the input string.

Summary

Congratulations on reading to the end of this tutorial. The TypeError: ‘str’ object does not support item assignment occurs when you try to change a string in-place using the indexing operator []. You cannot modify a string once you create it. To solve this error, you need to create a new string based on the contents of the existing string. The common ways to change a string are:

  • List comprehension
  • The String replace() method
  • += Operator

For further reading on TypeErrors, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨