Ошибка str object does not support item assignment

Performant methods

If you are frequently performing index replacements, a more performant and memory-compact method is to convert to a different data structure. Then, convert back to string when you’re done.

list:

Easiest and simplest:

s = "TEXT"
s = list(s)
s[1] = "_"
s = "".join(s)

bytearray (ASCII):

This method uses less memory. The memory is also contiguous, though that doesn’t really matter much in Python if you’re doing single-element random access anyways:

ENC_TYPE = "ascii"
s = "TEXT"
s = bytearray(s, ENC_TYPE)
s[1] = ord("_")
s = s.decode(ENC_TYPE)

bytearray (UTF-32):

More generally, for characters outside the base ASCII set, I recommend using UTF-32 (or sometimes UTF-16), which will ensure alignment for random access:

ENC_TYPE = "utf32"
ENC_WIDTH = 4

def replace(s, i, replacement):
    start = ENC_WIDTH * (i + 1)
    end = ENC_WIDTH * (i + 2)
    s[start:end] = bytearray(replacement, ENC_TYPE)[ENC_WIDTH:]


s = "TEXT HI ひ RA ら GA が NA な DONE"
s = bytearray(s, ENC_TYPE)
replace(s, 1, "_")
s = s.decode(ENC_TYPE)

Though this method may be more memory-compact than using list, it does require many more operations.

Представим такое: студент только что окончил школу, где изучал Паскаль. В универе на лабораторной по Python ему дали такое задание: заменить в строке все точки на восклицательные знаки.

Студент помнит, что можно обращаться к отдельным элементам строки, поэтому сразу пишет очевидный цикл:

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# делаем цикл, который переберёт все порядковые номера символов в строке
for i in range(len(s)):
    # если текущий символ — точка
    if s[i] == '.':
        # то меняем её на восклицательный знак    
        s[i] = '!'

Но после запуска компьютер выдаёт ошибку:

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

Казалось бы, почему? Есть строка, можно обратиться к отдельным символам, цикл в порядке — что не так-то?

Что это значит: интерпретатор сообщает нам, что не может поменять символ в строке один на другой.

Когда встречается: когда в Python мы пытаемся напрямую заменить символ в строке, как это делали в Паскале или некоторых других языках, которые это умеют. В Python строки хоть и состоят из символов, которые можно прочитать по отдельности, но управлять этими символами он не даёт. 

Что делать с ошибкой TypeError: ‘str’ object does not support item assignment

Решение простое: нужно не работать с символами в строке напрямую, а собирать новую строку из исходной. А всё потому, что Python разрешает прибавлять символы к строке, считая их маленькими строками. Этим и нужно воспользоваться:

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# строка с результатом
r = ''
# делаем цикл, который переберёт все порядковые номера символов в исходной строке
for i in range(len(s)):
    # если текущий символ — точка
    if s[i] == '.':
        # то в новой строке ставим на её место восклицательный знак    
        r = r + '!'
    else:
        # иначе просто переносим символ из старой строки в новую
        r = r + s[i]
# выводим результат
print(r)

Но проще всего, конечно, использовать встроенную функцию replace():

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# встроенной функцией меняем точки на восклицательные знаки
s = s.replace('.','!')
# выводим результат
print(s)

Вёрстка:

Кирилл Климентьев

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.


Table of contents

  • Python TypeError: ‘str’ object does not support item assignment
  • Example
    • Solution #1: Create New String Using += Operator
    • Solution #2: Create New String Using str.join() and list comprehension
  • Summary

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:

  • How to Solve Python TypeError: object of type ‘NoneType’ has no len()
  • How to Solve Python TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
  • How to Solve Python TypeError: ‘tuple’ object does not support item assignment
  • How to Solve Python TypeError: ‘set’ object does not support item assignment

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!

Table of Contents
Hide
  1. How to Reproduce the Error
  2. How to Fix the Error
    1. Solution 1 – Create a new string by iterating the old string
    2. Solution 2- Creating a new string using a list
  3. Conclusion

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 'str' object does not support item assignment error.

How to Reproduce the Error

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.

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:PersonalIJSCodeprgm.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 of certain characters of a string using its index and assignment operator.

How to Fix the Error

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 – Create 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.

Python shows TypeError: 'str' object does not support item assignment error when you try to access and modify a string object using the square brackets ([]) notation.

To solve this error, use the replace() method to modify the string instead.

This error occurs because a string in Python is immutable, meaning you can’t change its value after it has been defined.

For example, suppose you want to replace the first character in your string as follows:

greet = "Hello, world!"

greet[0] = 'J'

The code above attempts to replace the letter H with J by adding the index operator [0].

But because assigning a new value to a string is not possible, Python responds with the following error:

Traceback (most recent call last):
  File ...
    greet[0] = 'J'
TypeError: 'str' object does not support item assignment

To fix this error, you can create a new string with the desired modifications, instead of trying to modify the original string.

This can be done by calling the replace() method from the string. See the example below:

old_str = 'Hello, world!'

# Replace 'H' with 'J'
new_str = old_str.replace('H', 'J')

print(new_str)  # Jello, world!

The replace() method allows you to replace all occurrences of a substring in your string.

This method accepts 3 parameters:

  • old — the substring you want to replace
  • new — the replacement for old value
  • count — how many times to replace old (optional)

By default, the replace() method replaces all occurrences of the old string:

old_str = 'Hello, world!'

# Replace 'l' with 'x'
new_str = old_str.replace('l', 'x')

print(new_str)  # Hexxo, worxd!

You can control how many times the replacement occurs by passing the third count parameter.

The code below replaces only the first occurrence of the old value:

old_str = 'Hello, world!'

# Replace 'l' with 'x'
new_str = old_str.replace('l', 'x', 1)

print(new_str)  # Hexlo, world!

And that’s how you can modify a string using the replace() method.

If you want more control over the modification, you can use a list.

Convert the string to a list first, then access the element you need to change as shown below:

greet = "Hello, world!"

# Convert the string into a list
str_as_list = list(greet)

# Replace 'H' with 'J'
str_as_list[0] = 'J'

# Merge the list as string with join()
new_string = "".join(str_as_list)

print(new_string)  # Jello, world!

After you modify the list element, merge the list back as a string by using the join() method.

This solution gives you more control as you can select the character you want to replace. You can replace the first, middle, or last occurrence of a specific character.

Another way you can modify a string is to use the string slicing and concatenation method.

Consider the two examples below:

old_str = "Hello, world!"

# Slice the old_str from index 1 to finish
# Add the letter 'J' in front of the string
new_str = 'J' + old_str[1:]

print(new_str)  # Jello, world!

# Change the letter 'w' to 'x'
# slice the old_str twice and concatenate them
new_str = string = old_str[:7] + 'x' + old_str[8:]

print(new_str)  # Hello, xorld!

In both examples, the string slicing operator is used to extract substrings of the old_str variable.

In the first example, the slice operator is used to extract the substring starting from index 1 to the end of the string with old_str[1:] and concatenates it with the character ‘J’ .

In the second example, the slice operator is used to extract the substring before index 7 with old_str[:7] and the substring after index 8 with old_str[8:] syntax.

Both substrings are joined together while putting the character x in the middle.

The examples show how you can use slicing to extract substrings and concatenate them to create new strings.

But using slicing and concatenation can be more confusing than using a list, so I would recommend you use a list unless you have a strong reason.

Conclusion

The Python error TypeError: 'str' object does not support item assignment occurs when you try to modify a string object using the subscript or index operator assignment.

This error happens because strings in Python are immutable and can’t be modified.

The solution is to create a new string with the required modifications. There are three ways you can do it:

  • Use replace() method
  • Convert the string to a list, apply the modifications, merge the list back to a string
  • Use string slicing and concatenation to create a new string

Now you’ve learned how to modify a string in Python. Nice work!

  • Ошибка store data structure corruption windows 10
  • Ошибка stopcode windows 10 что делать
  • Ошибка stopcode memory management
  • Ошибка stop vehicle рено сценик 3
  • Ошибка stop c000021a fatal system error windows 7 как исправить