Представим такое: студент только что окончил школу, где изучал Паскаль. В универе на лабораторной по 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)
Вёрстка:
Кирилл Климентьев
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.
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
- How to Reproduce the Error
- How to Fix the Error
- Solution 1 – Create a new string by iterating the old string
- Solution 2- Creating a new string using a list
- 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.
Strings in Python are immutable. This means that they cannot be changed. If you try to change the contents of an existing string, you’re liable to find an error that says something like “‘str’ object does not support item assignment”.
In this guide, we’re going to talk about this common Python error and how it works. We’ll walk through a code snippet with this error present so we can explore how to fix it.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
The Problem: ‘str’ object does not support item assignment
Let’s start by taking a look at our error: Typeerror: ‘str’ object does not support item assignment.
This error message tells us that a string object (a sequence of characters) cannot be assigned an item. This error is raised when you try to change the value of a string using the assignment operator.
The most common scenario in which this error is raised is when you try to change a string by its index values. The following code yields the item assignment error:
string = "Banana" string[0] = "A"
You cannot change the character at the index position 0 because strings are immutable.
You should check to see if there are any string methods that you can use to create a modified copy of a string if applicable. You could also use slicing if you want to create a new string based on parts of an old string.
An Example Scenario
We’re going to write a program that checks whether a number is in a string. If a number is in a string, it should be replaced with an empty string. This will remove the number. Our program is below:
name = input("Enter a username: ") for c in range(len(name)): if not name[c].isnumeric(): name[c] = "" print(name)
This code accepts a username from the user using the input() method. It then loops through every character in the username using a for loop and checks if that character is a number. If it is, we try to replace that character with an empty string. Let’s run our code and see what happens:
Enter a username: pythonista101 Traceback (most recent call last): File "main.py", line 5, in <module> name[c] = "" TypeError: 'str' object does not support item assignment
Our code has returned an error.
The cause of this error is that we’re trying to assign a string to an index value in “name”:
The Solution
We can solve this error by adding non-numeric characters to a new string. Let’s see how it works:
name = input("Enter a username: ") final_username = "" for c in range(len(name)): if not name[c].isnumeric(): final_username += name[c] print(final_username)
This code replaces the character at name[c] with an empty string.
We have created a separate variable called “final_username”. This variable is initially an empty string. If our for loop finds a character that is not a number, that character is added to the end of the “final_username” string. Otherwise, nothing happens. We check to see if a character is a number using the isnumeric() method.
We add a character to the “final_username” string using the addition assignment operator. This operator adds one value to another value. In this case, the operator adds a character to the end of the “final_username” string.
Let’s run our code:
Enter a username: pythonista101 pythonista
Our code successfully removed all of the numbers from our string. This code works because we are no longer trying to change an existing string. We instead create a new string called “final_username” to which we add all the letter-based characters from our username string.
Conclusion
In Python, strings cannot be modified. You need to create a new string based on the contents of an old one if you want to change a string.
The “‘str’ object does not support item assignment” error tells you that you are trying to modify the value of an existing string.
Now you’re ready to solve this Python error like an expert.