To fix the TypeError: ‘str’ object does not support item assignment error in Python, there are two solutions we have effectively tested. Follow the article to better understand.
What causes this error?
The “TypeError: ‘str’ object does not support item assignment” error happens when you try to change a character. In Python, strings are immutable so this is the cause of this errors.
Example:
myStr = 'John' myStr[0] = 'f'
Output:
Traceback (most recent call last):
File "prog.py", line 2, in <module>
myStr [0] = 'f'
TypeError: 'str' object does not support item assignment
You cannot modify a single character of the string.
How to solve TypeError: ‘str’ object does not support item assignment in Python?
Using the ‘list()‘ method
Example:
- Convert the string with the character to be changed to a list.
- Change list items at a specific index.
- Join the items in the list into a new string.
myStr = '*LearnShareIT*' myList = list(myStr) print(myList) # Change list items at a specific index myList[0] = 'Hi' # Join the items in the list into a new string newString = ''.join(myList) print(newString)
Output:
['*', 'L', 'e', 'a', 'r', 'n', 'S', 'h', 'a', 'r', 'e', 'I', 'T', '*']
HiLearnShareIT*
Note:
- Since the list is mutable, it is possible for you to change the list items.
- The
str.join()
method gets all the items in an iterable and joins them into a string. You must specify a string as the separator. In the example above, the string is separated by a empty''
character.
Using the ‘replace()’ method
The replace()
method replaces a phrase with another specified phrase.
Syntax:
string.replace(oldvalue, newvalue, count)
Parameters:
- oldvalue: the string you want to replace.
- newvalue: the string that you will replace in place of ‘oldvalue’.
- count: (optional) shows the number of occurrences of the string ‘oldvalue’ (the string you want to replace).
Example 1:
myStr = "a a b b c c d d" result = myStr.replace("a", "g") print(result)
Output:
g g b b c c d d
Example 2:
myStr = "a a b b c c d d" result = myStr.replace("a", "g", 1) print(result)
Output:
g a b b c c d d
The first ‘a’ of the string is replaced with the letter ‘g’.
Summary
In this tutorial, I’ve explained how to solve the TypeError: ‘str’ object does not support item assignmen in Python. If you have any questions about this issue, please comment below. I will answer your questions. Thanks for reading!
Maybe you are interested:
- TypeError: a bytes-like object is required, not ‘str’ in python
- Typeerror: can only concatenate str (not “int”) to str
- TypeError: cannot unpack non-iterable int object in Python
- TypeError: cannot unpack non-iterable NoneType object
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java