"TypeError: string indices must be integer" when trying to make a 2D array in python

I am so new to python (and coding) and I just want to create a board (for a console game) based on the desire of the player.

Mainly...

import array print("What size do you want the board?") Boardsize = input() Tablero = array('b' [Boardsize, Boardsize]) for w in Boardsize: for h in Boardsize: Boardsize(w)(h).append('.') print (Tablero) 

At least my idea, but the compiler says:

 Tablero = array('b'[Boardsize, Boardsize]) TypeError: string indices must be integers 
+6
source share
3 answers

What's happening

input() returns a string (characters you entered, for example, "123"), but you get a TypeError because you are passing a string to something that expects a number (like 123, without quotes).


Decision

The fix converts the string to a number, passing it through the int(...) constructor, for example. int(input()) (just like int("12") will give you 12 ).

I would like to apologize if you are not new to programming, and it was a stupid mistake, but in case you are new to, here is my thought process that helped me debug the problem. I hope you do not find this condescending; I share my thinking process, so others in such situations can correct such errors.


How to diagnose these problems

You debug this as follows, returning one step at a time:

The first test is for you to understand how to make an array correctly. For example, I would try to create a 3x3 array to make sure I understood the API.

 >>> array(..., [3,3]) <array object at 0x...> 

Ok, it worked! It seems we can make array right if we just enter the numbers array(..., [3,3]) . Now try with input() .

 >>> boardsize = input() >>> array(..., [boardsize, boardsize]) TypeError: string indices must be integers 

This is odd. I just created a 3x3 array(..., [3,3]) with array(..., [3,3]) , why doesn't array(..., [boardsize, boardsize]) ? Check if the boardsize value is boardsize :

 >>> boardsize '3' 

How strange the value seems to be 3 , right? Let me check to make sure.

 >>> boardsize == 3 False 

Wait, '3'! = 3 ??? How does "3" not match 3?

 >>> type(boardsize) <class 'str'> 

Ahh! ' I see that this is a string. It should be such that input returns a string. This makes sense, for example, I can enter "cat" and make boardsize == 'cat' , and I should not expect python to determine if an arbitrary string is a number.

 >>> '3' '3' >>> 3 3 >>> boardsize '3' 

The fix will be related to google for python convert string to number : second hit: "use the int(...) built-in function

tl; dr: Make your way back to error by checking yourself at every step. When you start making large programs, you can use automatically called health check functions and “unit tests” to make debugging easier.


(sidenote: If you are interested in how objects are printed, this comes from the special __repr__ method that all classes define. Calling repr(something) will pretty clearly show which object something ; repr automatically called at the output of what you enter into the interactive interpreter.)

+20
source

Let me suggest an answer that I think will help you debug. You said you got an error:

 Tablero = array('b'[Boardsize, Boardsize]) TypeError: string indices must be integers 

Consider the contents of the error. The index operator is the square brackets immediately after the variable, myvar[n] , and any n that you put between these square brackets will be considered the index of this variable myvar . Usually you index what are called "sequence types" (that is, list , tuple and string ) with integer indices. The message after your TypeError indicates that your code tried to index a string with something other than an integer. Here is an example that you can try in the interactive interpreter:

 >>> mystr = 'cool beans, bro!' # define a string (sequence type) >>> mystr # echo the value of the string by entering its name 'cool beans, bro!' >>> mystr[0] # sequence indices start at 0, so this gives us the first character 'c' >>> mystr[6] # similarly, the seventh character (index 6) 'e' >>> mystr['cool story, sis!'] # a string is not a valid index of a string TypeError: string indices must be integers 

But where, for example, in your code did you try to index the string? So, copy the square brackets right after any variable makes python assume that you are trying to access the value at some index. In your code 'b'[Boardsize, Boardsize] . If you want to pass both 'b' and [Boardsize, Boardsize] as parameters in your array constructor, you need to put a comma between these values, for example:

 Tablero = array('b', [Boardsize, Boardsize]) 

However, I would caution against using an array type in general if you don't think you have every reason. It's hard to see the logic of this, especially from some other programming paradigms, but in python it’s much easier to stick to the general list data structure when you can handle it. A list is a lot like array , but in the latter case, you have to say what size data you will give in advance, which is usually unreasonably specific, except when optimization is required taking into account memory management. To define a list, it is simple as:

 tablero = [ ] 

Pay attention to two things here. First, as a convention in python, most variable names should be lowercase or lower_with_underscores . Secondly, the square brackets do not immediately after the variable in this context means something completely different than the index operator: they denote the list constructor, which means that any values ​​separated by commas inside the brackets become the values ​​of the new list. So the expression

 [Boardsize, Boardsize] 

will give you a list containing two values ​​(respectively, Boardsize and Boardsize). I will leave it to you to figure out how to use the list type according to your needs, try the quick guide in the official documentation , and also note that you can create nested lists.

Thanks to ninjagecko for helping me brainstorm a useful answer.

+2
source

In the sample code

 Tablero = array('b'[Boardsize, Boardsize]) TypeError: string indices must be integers 

Integer indices are not allowed. To get the job done, you can declare DICT as follows:

 Tablero = {} Tablero = array('b'[Boardsize, Boardsize]) TypeError: string indices must be integers 

Hope this works for you.

0
source

Source: https://habr.com/ru/post/892871/


All Articles