"TypeError: string indices must be integers" when trying to make 2D array in python
I'm so kind of new to python (and coding) and I just want to create a board (for a console game) based on the player desire.
Basically it's this...
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:
Board开发者_JAVA百科size(w)(h).append('.')
print (Tablero)
At least that's my idea, but the compiler say:
Tablero = array('b'[Boardsize, Boardsize])
TypeError: string indices must be integers
What's going on
input()
returns a string (the characters you typed in, e.g. "123"), but you are getting a TypeError
because you are passing a string to something that expects a number (e.g. 123, without the quotes).
Solution
The fix is convert the string to a number by passing it through the int(...)
constructor, e.g. int(input())
(just like int("12")
will give you 12
).
I'd like to apologize if you are not new to programming and this was a silly mistake, but in case you are new, here was my thought process which helped me debug the issue. I hope you do not find it condescending; I am sharing my thought process so others in similar situations can fix similar bugs.
How to diagnose these kinds of issues
You would debug this as follows by backtracking one step at a time:
� First test to make sure that you understand how to make array
s properly. I would for example try to make an array of size 3x3 to make sure I understood the API.
>>> array(..., [3,3])
<array object at 0x...>
� Okay, that worked! We seem to be able to make array
s properly if I just type in the numbers array(..., [3,3])
. Now let's try with input()
.
>>> boardsize = input()
>>> array(..., [boardsize, boardsize])
TypeError: string indices must be integers
� This is odd. I just made a 3x3 array with array(..., [3,3])
, why doesn't array(..., [boardsize, boardsize])
work? Let's check what the value of boardsize
really is:
>>> boardsize
'3'
� How odd, the value seems to be 3
, right? Let me double-check to make sure.
>>> boardsize == 3
False
� Wait, '3'!=3 ??? How is '3' not the same as 3?
>>> type(boardsize)
<class 'str'>
� Ahah! The '
I see mean it is a string. It must be the case that input
returns a string. This makes sense, since for example I could type in "cat" and make boardsize == 'cat'
, and I should not expect python to be able to tell whether an arbitrary string is a number.
>>> '3'
'3'
>>> 3
3
>>> boardsize
'3'
� The fix would be to google for python convert string to number
: second hit: "use the built-in int(...)
function
tl;dr: Work your way backwards towards the error, sanity-checking yourself at each step. When you start making large programs, you can use automatically-called sanity check functions and "unit tests" to make debugging easier.
(sidenote: If you are curious how objects are printed out, it comes from the special __repr__
method that all classes define. Calling repr(something)
will show fairly unambiguously what kind of object something
is; repr
is automatically called on the output of what you type into the interactive interpreter.)
Let me offer an answer that I think will help you debug. You said you got the error:
Tablero = array('b'[Boardsize, Boardsize])
TypeError: string indices must be integers
Consider the content of the error. The index operator is square brackets immediately after a variable, myvar[n]
, and whatever n
you put in between those square brackets will be considered an index of that variable myvar
. You usually 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's an example that you can try yourself 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 in your code, you say, did you try to index a string? Well, putting square brackets immediately after any variable makes python assume you're trying to access a value at some index of it. Your code says 'b'[Boardsize, Boardsize]
. If you want to pass both 'b'
and [Boardsize, Boardsize]
as parameters to your array
constructor, you'll need to put a comma between these values, like:
Tablero = array('b', [Boardsize, Boardsize])
However I would caution against using the array
type at all, unless you think you have a very good reason to. It's tough to see the logic of this, especially coming from some other programming paradigms, but in python it's much simpler to stick with the generic list
data structure when you can get away with it. A list
is much like an array
but in the latter you have to tell it what size data you'll be giving it ahead of time, which is usually unnecessarily specific except when trying to highly optimize with respect memory management. To define a list it's as simple as:
tablero = [ ]
Note two things here. First, as a convention in python, most variable names should be lowercase
or lower_with_underscores
. Second, the square brackets not immediately after a variable in this context mean something entirely different from the indexing operator: they denote a list
constructor, meaning that any comma-separated values inside the brackets become the values of a new list. So the expression
[Boardsize, Boardsize]
would give you a list containing two values (Boardsize and Boardsize, respectively). I'll leave it to you to figure out how to use the list
type to suit your needs, try the brief tutorial in the official documentation, and note also that you can make nested lists.
Thanks to ninjagecko for helping me brainstorm a useful answer.
For the example code
Tablero = array('b'[Boardsize, Boardsize])
TypeError: string indices must be integers
Integer indices are not allowed. To get it working you can declare the DICT as specified below:
Tablero = {}
Tablero = array('b'[Boardsize, Boardsize])
TypeError: string indices must be integers
Hope this works for you.
精彩评论