In this article, we will be discussing the TypeError:’str’ Object Does Not Support Item Assignment exception.
We will also be going through solutions to this problem with example programs.
Why is This Error Raised?
When you attempt to change a character within a string using the assignment operator, you will receive the Python error TypeError: ‘str’ object does not support item assignment.
As we know, strings are immutable. If you attempt to change the content of a string, you will receive the error TypeError: ‘str’ object does not support item assignment.
There are four other similar variations based on immutable data types:
TypeError: 'tuple' object does not support item assignment
TypeError: 'int' object does not support item assignment
TypeError: 'float' object does not support item assignment
TypeError: 'bool' object does not support item assignment
Replacing String Characters using Assignment Operators
Replicate these errors yourself online to get a better idea here.
In this code, we will attempt to replace characters in a string.
myString = "PythonPool"
myString[0] = "p"
print(myString)
Output
Solution
Strings are an immutable data type. However, we can change the memory to a different set of characters like so:
myString = "PythonPool"
# same variable diff string stored in a diff memory location
myString = "pythonPool"
print(myString)
Output
pythonPool
TypeError: ‘str’ Object Does Not Support Item Assignment in JSON
Let’s review the following code, which retrieves data from a JSON file.
import json
with open('sample.json', 'r') as q:
l = q.read()
data = json.load(l)
data['sample'] = '{}'
data['sample]['content'] = 'PythonPool'
Output
TypeError: 'str' object does not support item assignment
Solution
In line 5, we are assigning data['sample']
to a string instead of an actual dictionary. This causes the interpreter to believe we are reassigning the value for an immutable string type.
import json
with open('sample.json', 'r') as q:
l = q.read()
data = json.load(l)
data['sample'] = {}
data['sample]['content'] = 'PythonPool'
TypeError: ‘str’ Object Does Not Support Item Assignment in PySpark
The following program reads files from a folder in a loop and creates data frames.
for yr in range (2014,2018):
cat_bank_yr = sqlCtx.read.csv(cat_bank_path+str(yr)+'_'+h1+'bank.csv000',sep='|',schema=schema)
cat_bank_yr=cat_bank_yr.withColumn("cat_ledger",trim(lower(col("sampleData"))))
cat_bank_yr=cat_bank_yr.withColumn("category",trim(lower(col("SampleCategory"))))
Output
TypeError: 'str' object is not callable
Solution
This occurs when a PySpark function is overwritten with a string. You can try directly importing the functions like so:
from pyspark.sql.functions import col, trim, lower
TypeError: ‘str’ Object Does Not Support Item Assignment in PyMongo
The following program writes decoded messages in a MongoDB collection. The decoded message is in a Python Dictionary.
dthandler = lambda obj: (
str(obj)
if isinstance(obj, Decimal)
or isinstance(obj, datetime.time)
else None
)
class Decoder(decoder.base.Base):
...
...
...
...
try:
...
...
...
x = json.dumps(context, default=dthandler)
print x
self.mongo_coll.insert(x) # ERROR LINE
except errors.OperationFailure as op:
print "Operation Exception"
..
...
print '^^^^^'
Output
Serialization Exception (mongo/write.py) 'str' object does not support item assignment
Solution
At the 10th visible line, the variable x is converted as a string.
It’s better to use:
self.mongo_coll.insert(msg)
Please note that msg
are a dictionary and NOT an object of context.
TypeError: ‘str’ Object Does Not Support Item Assignment in Random Shuffle
The below implementation takes an input main
and the value is shuffled. The shuffled value is placed into Second
.
from tkinter import *
import random
def randomize(a):
Second.delete(0 , 'end')
b = Main.get()
c = random.shuffle(b)
Second.insert(0 , c)
root = Tk()
Main = Entry(root)
Main.grid(row = 1,column = 0 , sticky = 'we')
...
...
...
Output
TypeError: 'str' Object Does Not Support Item Assignment
Solution
random.shuffle
is being called on a string, which is not supported. Convert the string type into a list and back to a string as an output in Second
def randomize(a):
Second.delete(0 , 'end')
b = Main.get()
c = list(b)
random.shuffle(c) # Converted to a list
Second.insert(0 , ''.join(c))
TypeError: ‘str’ Object Does Not Support Item Assignment in Pandas Data Frame
The following program attempts to add a new column into the data frame
import numpy as np
import pandas as pd
import random as rnd
df = pd.read_csv('sample.csv')
for dataset in df:
dataset['Column'] = 1
Output
TypeError: 'str' object does not support item assignment
Solution
The iteration statement for dataset in df:
loops through all the column names of “sample.csv”. To add an extra column, remove the iteration and simply pass dataset['Column'] = 1
.
import numpy as np
import pandas as pd
import random as rnd
df = pd.read_csv('sample.csv')
dataset['Column'] = 1
FAQs
These are the causes for TypeErrors
:
– Incompatible operations between 2 operands:
– Passing a non-callable identifier
– Incorrect list index type
– Iterating a non-iterable identifier.
The data types that support item assignment are:
– Lists
– Dictionaries
– and Sets
These data types are mutable and support item assignment
As we know, TypeErrors
occur due to unsupported operations between operands. To avoid facing such errors, we must:
– Learn Proper Python syntax for all Data Types.
– Establish the mutable and immutable Data Types.
– Figure how list indexing works and other data types that support indexing.
– Explore how function calls work in Python and various ways to call a function.
– Establish the difference between an iterable and non-iterable identifier.
– Learn the properties of Python Data Types.
Conclusion
We have looked at various error cases in TypeError:’str’ Object Does Not Support Item Assignment. Solutions for these cases have been provided. We have also mentioned similar variations of this exception.