0

I am trying to modify my 2D tab but python shows me the following error:

tab[Lig][Col] = car

TypeError: 'str' object does not support item assignment

tab = input().split(' ')
nbLignes = int(tab[0])
nbColonnes = int(tab[1])
nbRectangles = int(input())
tableau = [["."] * nbColonnes for m in range(nbLignes)]

for k in range(nbRectangles):
   tab2 = input().split(' ')
   iLig1=int(tab2[0])
   iLig2=int(tab2[2])
   iCol1=int(tab2[1])
   iCol2=int(tab2[3])
   car=tab2[4]
   caractere = tab2[4]
   for Lig in range(iLig1,iLig2+1):
      for Col in range(iCol1,iCol2+1):
         tab[Lig][Col] = car
for Lig in range (nbLignes):
   for Col in range(nbColonnes):
      print(tab[Lig][Col],sep= ' ')
Cere
  • 1
  • 1
  • I can't find `tempLig[Col] = car` in the code you provided. Also, what is the value of `tab` at the beginning? – sal Jul 29 '19 at 17:19
  • Sorry, the line is: ```tab[Lig][Col]``` (I edited the post) and for the value of the first tab: it is two integers – Cere Jul 29 '19 at 17:21
  • Thank you. You cannot change the character inside a string like that, as it is immutable. Read this post: https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python – sal Jul 29 '19 at 17:23
  • Thanks for your replys, I know that strings are immutable, the problem was that i was trying to modify "tab" wich is a string and not "tableau" who is the tab I actually wanted to modify. – Cere Jul 29 '19 at 17:29

1 Answers1

0

Looking at your code:

tab = input().split(' ')

This tells me that tab is a list of str.

In [1]: tab = input().split(' ')                                                        
Hello there. How are you?
Out[1]: ['Hello', 'there.', 'How', 'are', 'you?']

So when you say tab[Lig][Col] = car, you are trying to change a letter in a string. And in Python, strings are immutable. Hence the error:

In [2]: test = 'foo'                                                                                     
Out[2]: 'foo'

In [3]: test[1]                                                                                          
Out[3]: 'o'

In [4]: test[0]                                                                                          
Out[4]: 'f'

In [5]: test[2] = 'b'                                                                                    
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-b8fb07018fbc> in <module>
----> 1 test[2] = 'b'

TypeError: 'str' object does not support item assignment
Roland Smith
  • 42,427
  • 3
  • 64
  • 94