Getting exception on Colab

Topic - Cleaning and Preparing Data in Python
Chapter - 4

Below code run successfully on DataQuest editor .
for row in moma:
nationality = row[2]
gender = row[5]
nationality = nationality.replace("(","")
nationality = nationality.replace(")","")
row[2] = nationality
gender = gender.replace("(","")

But on Colab it is throwing below exception
TypeError Traceback (most recent call last)
in ()
3 nationality = nationality.replace("(","")
4 nationality = nationality.replace(")","")
----> 5 row[2] = nationality
6 gender = row[5]
7 gender = gender.replace("(","")

TypeError: ‘str’ object does not support item assignment

Can you please do the following things?

  • Share the Google Colab link.
  • Link to the corresponding screen in app.dataquest.io
  • Write a title according to these guidelines.

Thanks.

1 Like

String is an immutable object. That is, you cannot modify the string to change its value. Hence, a str object cannot support item assignment.

Most likely, row is a string object.
You can convert the string into a list and modify the content and reconvert it back to a string.

# Convert a string to its list representation
row = list(row)

# Modify the string character at index 2
row[2] = "s"

# Convert back to a string
row = "".join(row)

Hey @ssinghtest,

To add onto @Bruno’s suggestion, please use markdown to format the block.

Transform the text from

x = 67
for i in range(100):
if i < x:
print(i)
else:
print(x+i)

by using ``` triple back ticks to format a block of code to show indent

```
x = 67
for i in range(100):
if i < x:
print(i)
else:
print(x+i)
```

, and transform the code into the following:

x = 67
for i in range(100):
   if i < x:
       print(i)
   else:
       print(x+i)
1 Like

@Bruno
Colab link -
https://colab.research.google.com/drive/1GGZ4jCtEI7e9BFhJoTMVFPT5OHzi3kKY#scrollTo=a3ycBhptmRIa
DataQuest Link -
https://app.dataquest.io/m/351/cleaning-and-preparing-data-in-python/4/cleaning-the-nationality-and-gender-columns

Thanks & Regards,
Santosh Singh

Hey, Santosh. I can’t access the Google Colab link. I’ve requested permission.

@Bruno Colab link is shared now. Could you please try again

In your notebook you’re reading the data into a pandas.DataFrame object. So when you do for row in moma, by virtue of how the iterators are implemented in dataframes, you’ll actually be iterating over the columns of the dataframe, which are strings.

In the mission we do not read the file into a dataframe, we represent the data as a list of lists. If you want to use dataframes, you need to adjust the techniques.